我正在阅读有关生命的 rust 迹文件.我试过这样的方法:
struct S {
x: i8,
}
impl S {
fn fun(self) {}
fn print(&self) {
println!("{}", self.x);
}
}
fn main() {
let s = S { x: 1 };
s.fun();
s.print();
}
我得到以下错误:
error[E0382]: borrow of moved value: `s`
--> src/main.rs:16:5
|
15 | s.fun();
| - value moved here
16 | s.print();
| ^ value borrowed here after move
|
= note: move occurs because `s` has type `S`, which does not implement the `Copy` trait
这是因为fun(self)
方法拥有s
实例的所有权.这可以通过更改为fun(&self)
来解决.
我不明白你为什么想要一个对象上的方法控制自己.我只能想到一个例子,一个析构函数方法,但是如果你想处理这个对象,那么它无论如何都会由对象的所有者来处理(在这个例子中,范围是main
).
为什么可以编写一个拥有 struct 所有权的方法?在任何情况下,你会想要这个吗?