gpt4 book ai didi

rust - &self 和 self 有什么区别?

转载 作者:行者123 更新时间:2023-12-03 08:09:22 29 4
gpt4 key购买 nike

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

最佳答案

&self 使用结构/枚举创建的变量被函数借用意味着未给出所有权。创建变量的函数将拥有所有权。

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();


}

关于rust - &self 和 self 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71275656/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com