Cast an `i32` to a `#[repr(i32)]` Enum?

I can cast a #[repr(i32)] enum to an i32, but it doesn't let me do it in the other direction. Is there a way that I've missed that will let you do that, or does it only go one way?

I'm assuming transmute would work, but that's a big no-no for such a simple case I immagine. :slight_smile:

You could do a transmute, but in Rust having an enum value where the discriminant isn't one of the predefined variants is undefined behavior. So you would need to check that the i32 matches one of the enum variants before doing the transmute.

I imagine you could implement TryFrom with an internal unsafe block that does the check and then does the transmute. The strum crate also has a trait that can help with this called FromRepr.

2 Likes

OK, yeah, the as works because it will always succeed, but a TryFrom would be necessary because taking any i32 isn't necessarily going to make one of my enum variants, duh. :man_facepalming:

Thank you!

You can use num-derive crate for this: https://crates.io/crates/num-derive

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.