I can get an integer value of an enums like this:
enum MyEnum {
A = 1,
B,
C,
}
let x = MyEnum::C as i32;
but I can't seem to do this:
match x {
MyEnum::A => {}
MyEnum::B => {}
MyEnum::C => {}
_ => {}
}
How can I either match against the values of the enum or try to convert x
back to a MyEnum
?
I can see a function like this being useful for enums, but it probably doesn't exist:
impl MyEnum {
fn from<T>(val: &T) -> Option<MyEnum>;
}
I wrote a simple macro which converts the numerical value back to the enum:
You can use it like this:
You can derive
FromPrimitive
. Using Rust 2018 simplified imports syntax:In your
Cargo.toml
:More details in num-derive crate, see esp. sample uses in tests.
If you're sure the values of the integer are included in the enum, you can use
std::mem::transmute
.This should be used with
#[repr(..)]
to control the underlying type.Complete Example:
Note that unlike some of the other answers, this only requires Rust's standard library.
You can take advantage of match guards to write an equivalent, but clunkier, construction:
std::mem::transmute
can also be used:But this requires that you know the size of the enum, so you can cast to an appropriate scalar first, and will also produce undefined behavior if
x
is not a valid value for the enum.If the integer you are matching on is based on the order of the variants of the enum, you can use strum to generate an iterator of the enums and take the correct one:
std::num::FromPrimitive
is marked as unstable and will not be included in Rust 1.0. As a workaround, I wrote theenum_primitive
crate, which exports a macroenum_from_primitive!
that wraps anenum
declaration and automatically adds an implementation ofnum::FromPrimitive
(from thenum
crate). Example: