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

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.


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.

Tags:

Ownership

Rust