如果 str 不实现 Copy 特性,如何复制它?
How can str be copied if it doesn't implement the Copy trait?
"The str
type, also called a 'string slice', is the most primitive [emphasis added] string type." (https://doc.rust-lang.org/std/primitive.str.html)
因此,直觉上 str
应该是可复制的,它是:
fn main() {
let _str = "hello";
let _str2 = _str;
println!("{}", _str); // Output: hello
}
但是,它没有实现 Copy
特性:
fn main() {
is_copy::<str>(); // Compile time error: the trait std::marker::Copy is not implemented for str
}
fn is_copy<T: Copy>() {}
是什么允许 str
这种类似复制的行为?
"abc"
比 多 str
。它实际上是一个参考:
fn name_of_val<T>(_: T) {
println!("{:?}", std::any::type_name::<T>());
}
name_of_val("abc");
//Prints "&str".
因此,我们不能直接看str
的实现,而是要看traits的&T
(Reference)的实现。
我们有一个副本实现:
impl<'_, T> Copy for &'_ T
where
T: ?Sized;
这满足&str
。但是由于 str
没有大小,我们不能为它实现复制,因为它是字符串中的数据,而不是 pointer/reference/(size, ptr)
。因此,我们无法对 str
按位执行 Copy
,因为我们不知道要复制多少数据。
"The str
type, also called a 'string slice', is the most primitive [emphasis added] string type." (https://doc.rust-lang.org/std/primitive.str.html)
因此,直觉上 str
应该是可复制的,它是:
fn main() {
let _str = "hello";
let _str2 = _str;
println!("{}", _str); // Output: hello
}
但是,它没有实现 Copy
特性:
fn main() {
is_copy::<str>(); // Compile time error: the trait std::marker::Copy is not implemented for str
}
fn is_copy<T: Copy>() {}
是什么允许 str
这种类似复制的行为?
"abc"
比 多 str
。它实际上是一个参考:
fn name_of_val<T>(_: T) {
println!("{:?}", std::any::type_name::<T>());
}
name_of_val("abc");
//Prints "&str".
因此,我们不能直接看str
的实现,而是要看traits的&T
(Reference)的实现。
我们有一个副本实现:
impl<'_, T> Copy for &'_ T
where
T: ?Sized;
这满足&str
。但是由于 str
没有大小,我们不能为它实现复制,因为它是字符串中的数据,而不是 pointer/reference/(size, ptr)
。因此,我们无法对 str
按位执行 Copy
,因为我们不知道要复制多少数据。