In Rust, Clone
is a trait that specifies the clone
method (and clone_from
). Some traits, like StrSlice
and CloneableVector
specify a to_owned
fn. Why would an implementation need both? What is the difference?
I did an experiment with Rust strings, which have both methods, and it demonstrates that there is a difference, but I don't understand it:
fn main() {
test_clone();
test_to_owned();
}
// compiles and runs fine
fn test_clone() {
let s1: &'static str = "I am static";
let s2 = "I am boxed and owned".to_string();
let c1 = s1.clone();
let c2 = s2.clone();
println!("{:?}", c1);
println!("{:?}", c2);
println!("{:?}", c1 == s1); // prints true
println!("{:?}", c2 == s2); // prints true
}
fn test_to_owned() {
let s1: &'static str = "I am static";
let s2 = "I am boxed and owned".to_string();
let c1 = s1.to_owned();
let c2 = s2.to_owned();
println!("{:?}", c1);
println!("{:?}", c2);
println!("{:?}", c1 == s1); // compile-time error here (see below)
println!("{:?}", c2 == s2);
}
The compile time error for the to_owned
example is:
error: mismatched types: expected `~str` but found `&'static str`
(str storage differs: expected `~` but found `&'static `)
clone.rs:30 println!("{:?}", c1 == s1);
Why would the first example work but not the second?
~"abc"
with"abc".to_string()
– oli_obkto_string()
rather than the older '~' notation. However, it is interesting that this new version (your playground entry) now compiles and runs fine. Did a change in the==
operator/fn happen so that it can compare&str
andString
types for value equality? – quux00