在Rust中,Clone是一个指定clone方法(和clone_from)的特征.一些特质,比如StrSlice和CloneableVector 指定一个to_ownedFN.为什么实现需要两者兼而有之?有什么不同?
我做了一个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 …Run Code Online (Sandbox Code Playgroud) rust ×1