18.self关键字.rs

#[derive(Debug)]
struct MyType {
    name: String
}

impl MyType {
    fn do_something(self, age: u32) {
    //等价于 fn do_something(self: Self, age: u32) {
    //等价于 fn do_something(self: MyType, age: u32) {
        println!("name = {}", self.name);
        println!("age = {}", age);
    }

    fn do_something2(&self, age: u32) {
        println!("name = {}", self.name);
        println!("age = {}", age);
    }
}

fn test_1(){
    
    let my_type = MyType{name: "linghuyichong".to_string()};
    //使用self
    my_type.do_something(18);   //等价于MyType::do_something(my_type, 18);
    //println!("my_type: {:#?}", my_type);    //在do_something中,传入的是对象,而不是引用,因此my_type的所有权就转移到函数中了,因此不能再使用

    //使用&self
    let my_type2 = MyType{name: "linghuyichong".to_string()};
    my_type2.do_something2(18);
    my_type2.do_something2(18);
    println!("my_type2: {:#?}", my_type2);//在do_something中,传入是引用,函数并没有获取my_type2的所有权,因此此处可以使用
    println!("Hello, world!");
}

/*

所有的trait都定义了一个隐式的类型Self,它指当前实现此接口的类型。” ——Rust官方文档

self
当self用作函数的第一个参数时,它等价于self: Self。&self参数等价于self: &Self。&mut self参数等价于self: &mut Self。
Self
方法参数中的Self是一种语法糖,是方法的接收类型(例如,本方法所在的impl的类型)。
它可能出现在trait或impl中。但经常出现在trait中,它是任何最终实现trait的类型代替(在定义trait时未知该类型)。
*/

/* Self 和 super是没有任何联系的
mod t1{
    mod t21{
        pub fn fun1(){
            println!("-----");
        }
    }
    mod t22{
        pub fn fun2(){
            super::t21::fun1();
        }

        pub fn fun3(){
            Self::t21::fun1(); //编译不过
        }
    }
}
*/

fn main() {
    test_1();

}

猜你喜欢

转载自blog.csdn.net/liujiayu2/article/details/114387748