The “trait Clone is is not implemented” when deriving the trait Copy for Enum

霸气de小男生 提交于 2019-12-05 15:26:23

问题


The following code:

#[derive(Copy)]
enum MyEnum {
    Test
}

Is giving me this error: error: the trait core::clone::Clone is not implemented for the type MyEnum [E0277]

Why is that the case, and how do I fix it?


回答1:


The Copy trait is a subtrait of Clone, so you always need to implement Clone if you implement Copy:

#[derive(Copy, Clone)]
enum MyEnum {
    Test
}

This makes sense, as both Copy and Clone are ways of duplicating an existing object, but with different semantics. Copy can duplicate an object by just copying the bits that make up the object (like memcpy in C). Clone can be more expensive, and could involve allocating memory or duplicating system resources. Anything that can be duplicated with Copy can also be duplicated with Clone.




回答2:


This happens because the trait Copy, depends on the trait Clone. The compiler will not try to infer and implement the trait for you. So you must explicitly implement the Clone trait as well.

Like that:

#[derive(Copy,Clone)]
enum MyEnum {
  Test
}


来源:https://stackoverflow.com/questions/30782836/the-trait-clone-is-is-not-implemented-when-deriving-the-trait-copy-for-enum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!