Cloning from &T to T

An API I'm calling gives me &T. I want to keep an owned copy of it, T. How should it do that? Is ToOwned the answer, i.e. T needs to implement ToOwned?

1 Like

In your case, the answer is Clone. It's exactly what you need to go from &T to T.
ToOwned is for more complicated cases, e. g. when you want to go from &str to String.

ToOwned or Clone would work; ToOwned is blanked impl'd for anything that's Clone, so I don't really see any downside to requiring ToOwned.

2 Likes

I'd also prefer ToOwned, it communicates the intent better.

Also, ToOwned will apply for more types thanks to the blanket impl that vitaly mentions. So with ToOwned, your API will be usable in more cases. (anything that is Clone, plus things that have custom ToOwned logic, such as &str->String, or [T]->Vec<T>).

As the ToOwned doc says:

The ToOwned trait generalizes Clone to construct owned data from any borrow of a given type.

(emphasis mine)

:+1: to @vitalyd's point. While technically clone is &T -> T, I tend to think of it as T -> (T,T) ("I want another one of these things I already have"), and prefer ToOwned for &T -> T ("Someone lent me something and I want my own copy to mess with").

3 Likes

Thanks guys. Makes sense :slight_smile: I'll have ToOwned implemented.