rust语法super、self和Self

当调用模块的函数时,需要指定完整的路径。
1)use关键字包括范围内的所有模块。 因此,可以直接调用函数,而不必在调用函数时包含模块。Rust中的use关键字缩短了调用函数的长度,使函数的模块在范围内。
2)使用 * 运算符
*运算符用于将所有项目放入范围,这也称为glob运算符。 如果使用glob运算符,那么不需要单独指定枚举变量。
3)使用 super 关键字
super关键字用于从当前模块访问父模块,它使能够访问父模块的私有功能。

复制代码
//self
struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height  //结构实例,"."
    }
}

fn foo() {}

fn bar() {
    self::foo();  //本模块,::
}

fn main() {}

//Self
trait T {
    type Item;  //关联类型
    const C: i32;  //常量,书里没讲,更没在特性里见过。说明特性可以有常量

    fn new() -> Self;  //实施者的类型

    fn f(&self) -> Self::Item;  //实施时决定
}

struct S; //空结构

impl T for S {
    type Item = i32;  //具体化
    const C: i32 = 9;  //特性里的数据赋值

    fn new() -> Self {           // 类型S
        S
    }

    fn f(&self) -> Self::Item {  // i32
        Self::C                  // 9, 此时没有实例,实施的是类型
    }
}


//super
mod a {
    pub fn foo() {}
}
mod b {
    pub fn foo() {
        super::a::foo(); // 父模块
    }
}
fn main() {}

//串联
mod a {
    fn foo() {}

    mod b {
        mod c {
            fn foo() {
                super::super::foo(); // call a's foo function
                self::super::super::foo(); // call a's foo function
            }
        }
    }
}
fn main() {}
复制代码

 

posted @   coxer  阅读(190)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示