[英]The “trait Clone is is not implemented” when deriving the trait Copy for Enum
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] 给我这个错误:错误:特征
core::clone::Clone
未实现类型MyEnum
[E0277]
Why is that the case, and how do I fix it? 为什么会这样,我该如何解决?
The Copy
trait is a subtrait of Clone
, so you always need to implement Clone
if you implement Copy
: 该
Copy
特点是的subtrait Clone
,所以你总是需要实现Clone
如果实现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
和Clone
都是复制现有对象的方式,但具有不同的语义。 Copy
can duplicate an object by just copying the bits that make up the object (like memcpy
in C). Copy
可以通过复制构成对象的位来复制对象(如C中的memcpy
)。 Clone
can be more expensive, and could involve allocating memory or duplicating system resources. Clone
可能更昂贵,并且可能涉及分配内存或复制系统资源。 Anything that can be duplicated with Copy
can also be duplicated with Clone
. 任何可以与
Copy
也可以与Clone
重复。
This happens because the trait Copy
, depends on the trait Clone
. 这是因为特征
Copy
取决于特征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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.