num_enum
Procedural macros to make inter-operation between primitives and enums easier.
Turning an enum into a primitive
extern crate num_enum;
use IntoPrimitive;
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.
Turning a primitive into an enum with try_from (nightly only)
extern crate num_enum;
use TryFromPrimitive;
use TryInto;
Turning a primitive into an enum (stable rust)
Unfortunately, try_from
is not yet stable (see https://github.com/rust-lang/rust/issues/33417), so num_enum
can also derive a custom trait which can be used in stable rust. It's a little ugly, but it does the job! It adds a function called try_into_{enum_name}
which you can use. If you're converting outside of the module where the enum was defined, you may also need to use your_module::TryInto{enum_name};
.
extern crate num_enum;
use CustomTryInto;
Optional features
Some enum values may be composed of complex expressions, for example:
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.