3

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

StyMaar
  • 43
  • 4

1 Answers1

3

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.

Erik Tate
  • 131
  • 4
  • Please, do not answer to duplicates. Your solution is already there: https://stackoverflow.com/a/28029667/4498831 – Boiethios May 03 '19 at 15:25