This is a custom derive, using procedural macros, implementation of enum_primitive.
https:/docs.rs/enum-primitive-derive/
Add the following to Cargo.toml
:
[dependencies]
enum-primitive-derive = "^0.1"
num-traits = "^0.1"
Then to your code add:
```rust
extern crate enumprimitivederive; extern crate num_traits;
enum Variant { Value = 1, Another = 2, } ```
To be really useful you need use num_traits::FromPrimitive
or
use num_traits::ToPrimitive
or both. You will then be able to
use
numtraits::FromPrimitive
and/or
numtraits::ToPrimitive
on your enum.
```rust
extern crate enumprimitivederive; extern crate num_traits;
use num_traits::{FromPrimitive, ToPrimitive};
enum Foo { Bar = 32, Dead = 42, Beef = 50, }
fn main() { asserteq!(Foo::fromi32(32), Some(Foo::Bar)); asserteq!(Foo::fromi32(42), Some(Foo::Dead)); asserteq!(Foo::fromi64(50), Some(Foo::Beef)); asserteq!(Foo::fromisize(17), None); asserteq!(Foo::Bar::toi32(), Some(32)); asserteq!(Foo::Dead::toisize(), Some(42)); } ```