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

前端 未结 2 1327
感动是毒
感动是毒 2021-01-05 04:57

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

struct S {
    x: i8,
}

impl S {
    fn fun(self) {}

    fn print(&se         


        
2条回答
  •  太阳男子
    2021-01-05 05:09

    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.

    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.

提交回复
热议问题