Trait enumscribe::TryUnscribe
source · pub trait TryUnscribe: Sized {
// Required method
fn try_unscribe(to_unscribe: &str) -> Option<Self>;
}
Expand description
Trait for converting from a string to an enum, or None
if the conversion fails.
Like all of the traits provided by enumscribe, this should not be implemented manually; use
#[derive(TryUnscribe)]
provided by the
enumscribe_derive crate instead.
Annotating a variant with #[enumscribe(case_insensitive)]
will cause case insensitive matching
to be used for that variant. If it is omitted, matching will be case sensitive.
When deriving this trait, you may specify the string that should map to a particular variant
by annotating it with #[enumscribe(str = "foo")]
. If this is omitted, the name of the variant
will be used instead.
use enumscribe::TryUnscribe;
#[derive(TryUnscribe, PartialEq, Eq, Debug)]
enum Airport {
#[enumscribe(str = "LHR", case_insensitive)]
Heathrow,
#[enumscribe(str = "LGW")]
Gatwick,
}
assert_eq!(Airport::try_unscribe("LHR"), Some(Airport::Heathrow));
assert_eq!(Airport::try_unscribe("lhr"), Some(Airport::Heathrow));
assert_eq!(Airport::try_unscribe("LGW"), Some(Airport::Gatwick));
assert_eq!(Airport::try_unscribe("lgw"), None);
assert_eq!(Airport::try_unscribe("STN"), None);
assert_eq!(Airport::try_unscribe("stn"), None);
Required Methods§
sourcefn try_unscribe(to_unscribe: &str) -> Option<Self>
fn try_unscribe(to_unscribe: &str) -> Option<Self>
Converts the given string to an enum variant, or None
if the conversion was not
successful.
The given string is matched against the #[enumscribe(str = "...")]
attribute for each
variant to determine which variant to return. If there was no successful match, the
variant marked with #[enumscribe(other)]
will be returned instead. If there is no
variant marked with #[enumscribe(other)]
, then None
will be returned.