What is the difference between clone and to_owned?
And when should you use one over the other?
ToOwned
is more flexible, implemented for all T: Clone
and a few extras. You can also use to_owned
on unsized types that don't implement Clone
but do have a related "owned" type, like str
to String
and [T]
to Vec<T>
. But if you're just going from a borrowed &T
to an owned T
, I'd stick to clone
.
(What cuviper said is correct, so feel free to ignore what I'm about to say.)
I like to think of .clone()
as "I already have a T, and I'd like another one" whereas I think of .to_owned()
as "I have something borrowed, and I want to make an owned copy so I can mess with it". So I'd do let x: T = ...; let y: T = x.clone();
but let x: &T = ...; let y: T = x.to_owned();
.
But that might just be my brain being weird. Technically the input to clone
is also borrowed, so the distinction is only stylistic.