Wynell
Wynell

Reputation: 795

What does "Clone works only for going from &T to T" mean in Rust documentation?

https://doc.rust-lang.org/std/borrow/trait.ToOwned.html

What does this mean?

But Clone works only for going from &T to T.

Could you please explain and give an example.

Upvotes: 3

Views: 109

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70900

Clone is the way to go from a shared reference to owned version. Consider e.g. Rc. <Rc as Clone>::clone() takes &Rc and produces Rc.

Now suppose you want to impl Clone for str. The clone() method will need to take &str and return str. But you cannot return str, since it's unsized - the compiler cannot know how much memory to save.

Instead, it needs to return String which is the owned version of str. But it cannot with Clone, since Clone hardcodes the return type to be equal to the input type.

This is the gap ToOwned fills. It provides a way to go from shared to owned versions, for things where the shared and owned versions are not of the same type.

ToOwned is thus a superset of Clone (indeed, every type that impls Clone also impls ToOwned by this blanket implementation).

Upvotes: 5

Related Questions