简体   繁体   English

导出Enum的特征副本时,“特征克隆未实现”

[英]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. 这是有道理的,因为CopyClone都是复制现有对象的方式,但具有不同的语义。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM