[英]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." “ str
类型,也称为‘字符串切片’,是最原始的[强调添加] 字符串类型。” ( https://doc.rust-lang.org/std/primitive.str.html ) ( https://doc.rust-lang.org/std/primitive.str.html )
Intuitively str
should therefore be copiable, which it is:因此,直觉上str
应该是可复制的,它是:
fn main() {
let _str = "hello";
let _str2 = _str;
println!("{}", _str); // Output: hello
}
However, it does not implement the Copy
trait:但是,它没有实现Copy
特性:
fn main() {
is_copy::<str>(); // Compile time error: the trait std::marker::Copy is not implemented for str
}
fn is_copy<T: Copy>() {}
What allows this copy-like behaviour with str
?是什么允许str
这种类似复制的行为?
"abc"
is more than just a str
. "abc"
不仅仅是一个更str
。 It is in fact a reference:它实际上是一个参考:
fn name_of_val<T>(_: T) {
println!("{:?}", std::any::type_name::<T>());
}
name_of_val("abc");
//Prints "&str".
Playground . 游乐场。
Therefore, we can't look at the str
implementations directly, instead we must look at the &T
(Reference) implementations of traits.因此,我们不能直接查看str
实现,而必须查看 trait 的&T
(Reference)实现。
We have a copy impl:我们有一个副本实现:
impl<'_, T> Copy for &'_ T
where
T: ?Sized;
This satisfies &str
.这满足&str
。 But since str
is unsized, we cannot impl copy for it, since it is the data in a string, not a pointer/reference/ (size, ptr)
to it.但是由于str
未确定大小,我们不能对其进行 impl copy ,因为它是字符串中的数据,而不是指向它的指针/引用/ (size, ptr)
。 We could therefore not do a bitwise Copy
of the str
since we wouldn't know how much data to copy.因此,我们无法对str
进行按位Copy
,因为我们不知道要复制多少数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.