小智 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)