Search code examples
enumsrust

How to create a Field-Less Enum variant from its discriminant?


If I want to know the discriminant of an enum variant, all I need to do is my_variant as usize (or whatever {integer} type). What if I have the discriminant, and I want to get the corresponding variant ?

I obviously tried the reverse my_int as MyEnum, but it (unsurprisingly) didn't work.

enum Enu {
    X,
    Y,
}

fn main() {
    let discr_x = Enu::X as usize;
    let x = magic(discr_x);
}

x should be Enu::X


Solution

  • There isn't a concise, built in way to do this in Rust. There are crates that help out with this sort of thing, such as enum_primitive, but depending on the number of enums you have, you might be better off implementing it yourself.

    I've done this sort of thing a few times:

    #[repr(u8)]
    pub enum Mode {
        Text,
        Code,
        Digits,
        AlphaNumeric,
    }
    
    impl Mode {
        pub fn from(mode: u8) -> Mode {
            match mode {
                0 => Mode::Text,
                1 => Mode::Code,
                2 => Mode::Digits,
                3 => Mode::AlphaNumeric,
                _ => Mode::Text,
            }
        }
    }
    

    Edit:

    This thread has some additional context about why this isn't possible by default.