最佳答案
在 Rust 中,Clone
是指定 clone
方法(和 clone_from
)的特性。一些特性,如 StrSlice
和 CloneableVector
指定 to_owned
fn。为什么一个实现需要两者?有什么区别吗?
我用 Rust 字符串做了一个实验,两种方法都有,它证明了两者之间的区别,但我不明白:
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);
}
to_owned
示例的编译时错误是:
error: mismatched types: expected `~str` but found `&'static str`
(str storage differs: expected `~` but found `&'static `)
clone.rs:30 println!("{:?}", c1 == s1);
为什么第一个例子可行,而第二个不行呢?