What is the difference between .clone() and .to_owned() in Rust?
Theto_owned()
trait docs explain the difference. Clone converts &T
to T
, but to_owned()
can convert from &T
to another target type. A good example is the impl of ToOwned for str, which returns a String
.You'd need to look at the impls for the type you are working with. They would probably do the same thing, but occasionally (as with str),
to_owned()
does a more complicated conversion. In fact, there is a blanket impl - so unless you see a specific impl, it's a bit simpler to call clone()
.