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

前端 未结 2 1324
感动是毒
感动是毒 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.

    0 讨论(0)
  • 2021-01-05 05:17

    Conversion from type A to type B commonly involves functions taking self by value. See the implementors of Into and From traits for concrete examples.

    0 讨论(0)
提交回复
热议问题