In Rust, what is the difference between clone() and to_owned()?
Solution 1:
.clone()
returns its receiver. clone()
on a &str
returns a &str
. If you want a String
, you need a different method, which in this case is .to_owned()
.
For most types, clone()
is sufficient because it's only defined on the underlying type and not on the reference type. But for str
and [T]
, clone()
is implemented on the reference type (&str
and &[T]
), and therefore it has the wrong type. It's also implemented on the owned types (String
and Vec<T>
), and in that case clone()
will return another owned value.
Your first example works because c1
and s1
(and c2
and s2
) have the same types. Your second example fails because they don't (c1
is String
whereas s1
is &str
). That's a perfect example of why the separate methods are necessary.
As of current Rust, both now compile, but in test_clone()
c1
is a String
and in test_to_owned()
it's a &str
. I'm pretty sure it compiles as Rust is now more lenient about automatically referencing and dereferencing values. In this particular example I believe the c1 == s1
line is compiled as though it said &*c1 == s1
. If you wish to prove the types involved you can add a deliberate type error, such as let _: i32 = c1;
and the error message will show the type.