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.