Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Rust require Copy and Clone traits for simple enum

Tags:

enums

rust

The following code will not compile unless Copy and Clone traits are derived in the enum. Why is this a requirement given that the enum is basically an i8 and according to the documentation, integers automatically implement the Copy trait? Related to this, since the size of MyEnum should be well known at compile time, shouldn't it go onto the stack? Doesn't the Clone trait imply that it goes on the heap?

#[derive(Debug, Copy, Clone)]
#[repr(i8)]
enum MyEnum {
    Some1,
}

fn main() {
    let x = MyEnum::Some1;
    let y = x;
    println!("x={:?} y={:?}", x, y);
}
like image 809
Paul Grinberg Avatar asked Aug 06 '26 18:08

Paul Grinberg


1 Answers

Clone has nothing to do with the heap. Clone does not imply heap-allocated for any type, be they structs, enums, and whether they have a #[repr] attribute or not. Clone is just a normal trait.

And traits aren't implemented automatically, ever, because when writing a library, this would be an implicit part of your public interface. That is, an type could be implicitly, and unexpectedly, Clone without the library author intending to make it Clone. This limits how the type could change in the future, and the library author might inadvertently break their public interface by changing the content of the type and losing that implicit trait implementation. Rust always prefers explicitness over hidden things.

like image 95
mcarton Avatar answered Aug 09 '26 13:08

mcarton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!