如何为包含字符串的类型(或任何未实现复制的类型)实现复制和克隆? [英] How do I implement Copy and Clone for a type that contains a String (or any type that doesn't implement Copy)?
问题描述
我在 Rust 中有一个枚举,它有一个带有 String
的值:
I have an enum in Rust which has one value that takes a String
:
#[derive(Clone, Copy)]
enum Simple {
Error(String),
Okay,
Foo([u32; 5]),
}
fn main() {
let x = Simple::Error(String::from("blah"));
let y = x.clone();
}
上面的枚举值 Foo
代表我使用的大约 10 个其他枚举,它们采用可复制的类型或数组.编译器似乎没有抱怨它们,只有 Error(String)
导致了这个:
The enum value Foo
above represents about 10 other enums I use that take copyable types or arrays of them. The compiler doesn't seem to complain about them, only the Error(String)
which causes this:
error[E0204]: the trait `Copy` may not be implemented for this type
--> src/main.rs:1:17
|
1 | #[derive(Clone, Copy)]
| ^^^^
2 | enum Simple {
3 | Error(String),
| ------ this field does not implement `Copy`
|
出于某种原因,String
是不可复制的.我不明白这个.我如何为枚举实现 Clone
仅针对一种类型的枚举,而在其余类型使用默认 impl 时出现问题?
For some reason, String
is not copyable. I don't get this. How do I implement Clone
for an enum for just the one type which has a problem while using the default impl for the rest?
推荐答案
复制
复制
指定类型,通过按位复制为其创建有效实例而不会使原始实例无效.
Copy
Copy
designates types for which making a bitwise copy creates a valid instance without invalidating the original instance.
这不适用于 String
,因为 String
包含一个指向堆上字符串数据的指针,并假定它对该数据具有唯一的所有权.当您删除 String
时,它会释放堆上的数据.如果您对 String
进行了按位复制,那么两个实例都会尝试释放相同的内存块,这是未定义行为.
This isn't true for String
, because String
contains a pointer to the string data on the heap and assumes it has unique ownership of that data. When you drop a String
, it deallocates the data on the heap. If you had made a bitwise copy of a String
, then both instances would try to deallocate the same memory block, which is undefined behaviour.
由于String
没有实现Copy
,你的enum
也不能实现Copy
strong> 因为编译器强制 Copy
类型仅由 Copy
数据成员组成.
Since String
doesn't implement Copy
, your enum
cannot implement Copy
either because the compiler enforces that Copy
types are composed only of Copy
data members.
克隆
仅仅提供了一个标准的clone
方法,由每个实现者决定如何实现它.String
确实实现了 Clone
,所以你可以把 #[derive(Clone)]
放在你的 enum 上代码>.
Clone
merely provides a standard clone
method, and it's up to each implementor to decide how to implement it. String
does implement Clone
, so you can put #[derive(Clone)]
on your enum
.
这篇关于如何为包含字符串的类型(或任何未实现复制的类型)实现复制和克隆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!