在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);
为什么第一个例子可以工作,而第二个不行?
https://stackoverflow.com/questions/22264502
复制相似问题