Derive enum from try into
Implements From
and TryInto
for enums
use ;
use TryInto;
assert_eq!;
let num: = B.try_into;
assert!;
Ignores variants with duplicate type definitions or named fields
use derive_enum_from_into::{EnumFrom, EnumTryInto};
use std::convert::TryInto;
#[derive(EnumFrom, EnumTryInto, PartialEq, Debug)]
enum Enum1 {
A(String),
B(String),
C {
something: bool
},
}
// Results in compile errors
let enum1: Result<String, _> = Enum1::A("Hello".to_owned()).try_into();
let enum1: Result<bool, _> = (Enum1::C { something: true }).try_into();
From
can be ignored for variants with #[from_ignore]
TryInto
can also be implemented for references of the enum. Specific variants can be ignored with #[try_into_ignore]
use ;
use TryInto;
let x = Number;
assert_eq!;
// This won't compile as cannot TryInto String
// assert!(TryInto::<String>::try_into(NumberOrString::String("Hello World".to_owned())).is_err());
// `TryInto` comes in handy for `filter_map` cases
// `TryInto` returns `self` if it does not match
assert_eq!;
Note that because of the default implementation of TryInto
the following will not compile. There are workarounds with wrapping X in a newtype pattern
#[derive(derive_enum_from_into::EnumTryInto)]
enum X {
Leaf(i32),
Nested(X)
}