&self 和 self 有什么区别?

Ale*_*ria 2 rust

我不清楚self和 之间有什么区别&self!因为在我的例子中两者都有效。

小智 5

&self使用结构/枚举创建的内容variable是由函数借用的,意味着未给出所有权。创建的函数variable将拥有所有权。

self函数执行后所有权被转移并且变量被销毁

struct User {
  name: String,
  id: i32
}
impl User {
    fn print_name(&self) -> () {
        println!("{}", self.name);
    }
    fn print_id(self) -> () {
        println!("{}", self.id);
    }
}

fn main() {
    let me = User { name: "Haider".to_owned(), id: 1234 };
    // me is borrowed so this means the variable is still owned by the `main` function we can call as many as functions until the ownership isn't transferred
     me.print_name();
     me.print_name();
     me.print_name();
     me.print_name();
     // ownership transferred and the `me` is destroyed after the execution of `me.print_id()` we will get error if run any other function on `me`
     me.print_id();
     // Error 
     me.print_name();

    
}
Run Code Online (Sandbox Code Playgroud)