#Is there any safe rust to fetch enum discriminant?

2 messages · Page 1 of 1 (latest)

lofty niche
#

For example, I have the following get_discriminant function, and I am wondering if there is any safe way to implement it.

#[repr(u32)]
enum MyEnum {
    One = 1,
    Ten(u32) = 10,
    Hundred(u32) = 100,
}

fn get_descriminant(e: &MyEnum) -> u32 {
    unsafe { *(e as *const MyEnum as *const u32) }
}

fn main() {
    let val_10 = MyEnum::Ten(42);
    println!("descriminant: {}", get_descriminant(&val_10));// this prints 10, as expected
}

When enum variants are associated with numeric values, explicitly assigning discriminants can be useful. For example, when serializing HttpStatus::NotFound into a binary representation, the value 404 can be read directly.

torn heron
#

There are crates but there isn't anything in std for this when the enum has data on variants