Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

enums

copy

rust

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?

like image 241
Tiago Engel Avatar asked Jun 11 '15 13:06

Tiago Engel


2 Answers

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.

like image 178
Shepmaster Avatar answered Oct 18 '22 18:10

Shepmaster


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
}
like image 35
diogovk Avatar answered Oct 18 '22 19:10

diogovk