Procedural macros to make inter-operation between primitives and enums easier. This crate is no_std compatible.
```rust use num_enum::IntoPrimitive;
enum Number { Zero, One, }
fn main() { let zero: u8 = Number::Zero.into(); assert_eq!(zero, 0u8); } ```
num_enum
's IntoPrimitive
is more type-safe than using as
, because as
will silently truncate - num_enum
only derives From
for exactly the discriminant type of the enum.
```rust use num_enum::TryFromPrimitive; use std::convert::TryFrom;
enum Number { Zero, One, }
fn main() { let zero = Number::tryfrom(0u8); asserteq!(zero, Ok(Number::Zero));
let three = Number::try_from(3u8);
assert_eq!(
three.unwrap_err().to_string(),
"No discriminant in enum `Number` matches the value `3`",
);
} ```
If you're really certain a conversion will succeed, and want to avoid a small amount of overhead, you can use unsafe
code to do this conversion. Unless you have data showing that the match statement generated in the try_from
above is a
bottleneck for you, you should avoid doing this, as the unsafe code has potential to cause serious memory issues in
your program.
```rust use num_enum::UnsafeFromPrimitive;
enum Number { Zero, One, }
fn main() { asserteq!( Number::Zero, unsafe { Number::fromunchecked(0u8) }, ); asserteq!( Number::One, unsafe { Number::fromunchecked(1u8) }, ); }
unsafe fn undefinedbehavior() { let _ = Number::fromunchecked(2); // 2 is not a valid discriminant! } ```
Some enum values may be composed of complex expressions, for example:
rust
enum Number {
Zero = (0, 1).0,
One = (0, 1).1,
}
To cut down on compile time, these are not supported by default, but if you enable the complex-expressions
feature of your dependency on num_enum
, these should start working.