Should simple enum derive Copy trait?


#1
use std::collections::HashMap;

//#[derive(Copy, Clone)]
enum SomeEnum {
    Some1,
    Some2,
}

struct SomeStruct {
    pub some_enum: SomeEnum,
    pub s: String,
}

fn proc_struct(some_struct: &SomeStruct) {
    let mut map = HashMap::new();
    map.insert(String::from("any"), 0);
    
    match map.get(&some_struct.s) {     // just for make a reference in SomeStruct
        Some(v) => {
            proc1(some_struct.some_enum);
            proc2(&some_struct.some_enum);
        }
        None => {}
    }
}

fn proc1(some: SomeEnum) {

}

fn proc2(some: &SomeEnum) {

}

fn main() {
    let some_struct = SomeStruct { some_enum: SomeEnum::Some1, s: String::from("s") };
    
    proc_struct(&some_struct);
}

Above code, show error:
proc1(some_struct.some_enum);
| ^^^^^^^^^^^ cannot move out of borrowed content

If add #[derive(Copy, Clone)] to SomeEnum, then it compiles ok.

Should simple enum like SomeEnum derive Copy trait ?
Any performance difference between function proc1() and proc2() ?


#2

There shouldn’t be any observable performance difference in this simple case. If anything, the enum value is smaller than the reference; that won’t matter for function calls where either the value or the reference is passed via a register, but it might make a difference if you’re storing an enum or a reference to the enum in a struct (not the case here, but thought I’d mention that anyway).

The bigger question here is of semantics. If your enum will continue to stay so simple, then copy/clone is fine. If not, you may want to hold off. Also, once you make them copy/clone, that’s part of its public API - removing later is a breaking change.


#3

For reference, this was cross-posted to Stack Overflow.


#4

Thanks, the answer is more detail than the one on Stack Overflow.