什么时候实现想要在 Rust 中获得 self 的所有权? [英] When would an implementation want to take ownership of self in Rust?

查看:43
本文介绍了什么时候实现想要在 Rust 中获得 self 的所有权?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读有关生命周期的 Rust 文档.我试过类似的东西:

I'm reading through the Rust documentation on lifetimes. I tried something like:

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) 来解决.

This is because the fun(self) method takes ownership of the s instance. This is solved by changing to fun(&self).

我不明白为什么你会想要一个对象的方法来控制自己.我只能想到一个例子,一个析构函数方法,但是如果你想处理对象,那么无论如何它都会由对象的所有者来处理(即 main 在这个范围内)例子).

I can't see why you would ever want to have a method on an object take control of itself. I can think of only one example, a destructor method, but if you wanted to do dispose of the object then it would be taken care of by the owner of the object anyway (i.e. scope of main in this example).

为什么可以编写一个获取结构所有权的方法?有没有什么情况是你想要这个的?

Why is it possible to write a method that takes ownership of the struct? Is there ever any circumstance where you would want this?

推荐答案

在 Rust 标准库文档中提到控制" self 的方法的惯用方式是说它消耗"它.如果您搜索此内容,您应该会找到一些示例:

The idiomatic way to refer to a method that "takes control" of self in the Rust standard library documentation is to say that it "consumes" it. If you search for this, you should find some examples:

  • Option::unwrap_or_default
  • A lot in the Iterator trait.

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

As to why: you can try rewriting Iterator::map — you would end up having a lifetime parameter wandering around that would quickly become unmanageable. Why? Because the Map iterator is based upon the previous one, so the borrow checker will enforce that you can only use one of the two at the same time.

这篇关于什么时候实现想要在 Rust 中获得 self 的所有权?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆