This crate exports a macro enum_from_primitive!
that wraps an
enum
declaration and automatically adds an implementation of
num::FromPrimitive
(reexported here), to allow conversion from
primitive integers to the enum. It therefore provides an
alternative to the built-in #[derive(FromPrimitive)]
, which
requires the unstable std::num::FromPrimitive
and is disabled in
Rust 1.0.
https://andersk.github.io/enumprimitive-rs/enumprimitive/
Add the following to your Cargo.toml
file:
[dependencies]
enum_primitive = "*"
Import the crate using #[macro_use] extern crate enum_primitive
, and
wrap your enum
declaration inside the enum_from_primitive!
macro.
```rust
extern crate num; use num::FromPrimitive;
enumfromprimitive! {
enum FooBar { Foo = 17, Bar = 42, Baz, } }
fn main() { asserteq!(FooBar::fromi32(17), Some(FooBar::Foo)); asserteq!(FooBar::fromi32(42), Some(FooBar::Bar)); asserteq!(FooBar::fromi32(43), Some(FooBar::Baz)); asserteq!(FooBar::fromi32(91), None); } ```