Ownership
On this page
The chapter on ownership in the Rust book is good to read and re-read periodically, even for experienced Rust programmers. It makes a bunch of concepts related to ownership much more explicit with practical examples, including coverage of often-taken-for granted concepts like &str
vs String
, Copy
vs Clone
, etc.
Reminder:
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
ToOwned
What’s the difference between Clone
and ToOwned
? The answer is in the docs:
Some types make it possible to go from borrowed to owned, usually by implementing the Clone trait. But Clone works only for going from
&T
toT
In other words, Clone
is for going from a reference of a type to an owned value of the same type. ToOwned
however has a required associated type which lets you return any other type. So you can go from &T
to U
. This is what “borrow-generalized” means.