Module num_enum
Type-safe conversions between enums and primitive numbers.
- Crate
::num_enum. - docs.rs
- crates.io
- GitHub
num_enum provides procedural macros for deriving type-safe conversions
between Rust enums and primitive numeric types.
While Rust's as operator can convert enums to numbers,
it can silently truncate values and doesn't provide safe conversions
in the reverse direction.
num_enum fills this gap with derive macros that generate
conversion implementations with proper error handling.
The primary derives are IntoPrimitive for converting enums to numbers,
and TryFromPrimitive for fallible conversion from numbers to enums.
For cases where all numeric values map to enum variants,
FromPrimitive provides infallible conversion,
and UnsafeFromPrimitive offers unsafe transmutation for performance-critical code.
Examples
Basic conversion between enums and numbers:
use ;
// Convert enum to number.
let code: u8 = Warning.into;
assert_eq!;
// Convert number to enum.
let status = try_from.unwrap;
assert_eq!;
// Invalid conversions return an error.
assert!;