一个实现什么时候想要在 Rust 中获得 self 的所有权?

When would an implementation want to take ownership of self in Rust?

我正在阅读有关生命周期的 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 的范围)。

为什么可以编写一个获取结构所有权的方法?在任何情况下你会想要这个吗?

从类型 A 到类型 B 的转换通常涉及通过值获取自身的函数。有关具体示例,请参阅 Into and From 特征的实现者。

在 Rust 标准库文档中引用 "takes control" of self 的方法的惯用方式是说它 "consumes" it。如果你搜索这个,你应该找到一些例子:

至于原因:您可以尝试重写 Iterator::map — 您最终会得到一个生命周期参数,很快就会变得难以管理。为什么?因为 Map 迭代器是基于前一个迭代器的,所以借用检查器将强制您只能同时使用两者之一。