Rust完全限定语法与消歧义:调用相同名称的方法

栏目: 编程语言 · Rust · 发布时间: 6年前

内容简介:Rust既不能避免一个下面示例代码说明了具体用法:运行结果:

Rust既不能避免一个 trait 与另一个 trait 拥有相同名称的方法,也不能阻止为同一类型同时实现这两个 trait 。甚至可以直接在类型上实现开始已经有的同名方法!当然,当调用这些同名方法时,你必须要告诉Rust我们使用哪一个。

下面示例代码说明了具体用法:

pub trait Airplane {
    fn speed(&self){
        println!("airplane default speed=800");
    }

    fn state(){
        println!("fly state");
    }
}

pub trait Boat {
    fn speed(&self);
    fn state(){
        println!("boat state");
    }
}

struct Airboat;

impl Airboat{
    fn speed(&self) {
        println!("airboat speed 0~800");
    }
    fn state(){
        println!("airboat state");
    }
}

impl Airplane for Airboat {
    fn speed(&self){
        println!("airboat in airplane state speed=800");
    }
}

impl Boat for Airboat {
    fn speed(&self){
        println!("airboat in boat state speed=60");
    }
}

fn main() {
    let a = Airboat;
    Airboat::state();
    a.speed();  //默认调用自身的实现
    <Airboat as Airplane>::state(); //完全限定语法
    Airplane::speed(&a);    //显示语法指定调用Airplane方法
    <Airboat as Airplane>::speed(&a);
    <Airboat as Boat>::state();
    Boat::speed(&a);
}
复制代码

运行结果:

airboat state
airboat speed 0~800
fly state
airboat in airplane state speed=800
airboat in airplane state speed=800
boat state
airboat in boat state speed=60
复制代码

通常,完全限定语法定义为: <Type as Trait>::function(receiver_if_method, next_arg, ...)

在存在调用相同名称方法时,重要的是告诉编译器你调用的是具体那个方法,上面的示例代码给出了调用相同名称时的调用方法。


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Probability and Computing: Randomization and Probabilistic Techn

Probability and Computing: Randomization and Probabilistic Techn

Michael Mitzenmacher、Eli Upfal / Cambridge University Press / 2017-7-3 / USD 62.23

Greatly expanded, this new edition requires only an elementary background in discrete mathematics and offers a comprehensive introduction to the role of randomization and probabilistic techniques in m......一起来看看 《Probability and Computing: Randomization and Probabilistic Techn》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具