How to implement Clone / Copy for an enum containing String?

I have an enumeration in Rust that has one value that String takes. This can be demonstrated with this simple example:

 #[derive(Clone, Copy)] enum Simple { Error(String), Okay, Foo([u32; 5]), } fn main() { let x = Simple::Error(String::from("blah")); let y = x.clone(); } 

The Foo enumeration value above represents about 10 other enumerations I use that take types or arrays to copy them. The compiler does not seem to complain about them, but only calls Error(String) :

 error: the trait `Copy` may not be implemented for this type; variant `Error` does not implement `Copy` [E0205] #[derive(Clone, Copy)] ^~~~ note: in this expansion of #[derive_Copy] (defined in src\main.rs) help: run `rustc --explain E0205` to see a detailed explanation 

For some reason, String not copied. I do not understand this. How to implement Clone to enumerate for only one type that has a problem when using the default value for the rest?

+6
source share
1 answer

Copy denotes types for which creating a bitwise copy creates a valid instance without invalidating the original instance. This does not apply to String , because String contains a pointer to the string data on the heap and assumes that it has a unique property of this data and therefore when you drop the String , it frees the data on the heap, and if you make a broken copy of String , then both instances will try to free the same block of memory that is undefined. Since String does not implement Copy , your enum cannot implement Copy either , because the compiler ensures that Copy types consist only of Copy members.

Clone simply provides a standard Clone method, and each developer must decide how to implement it. String implements Clone , so you can put #[derive(Clone)] on your enum .

+16
source

All Articles