Skip to content

Instantly share code, notes, and snippets.

@internetimagery
Last active December 31, 2019 09:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save internetimagery/a2fd6da5127676c05a8f12dc1deb132f to your computer and use it in GitHub Desktop.
Save internetimagery/a2fd6da5127676c05a8f12dc1deb132f to your computer and use it in GitHub Desktop.
Enum to and from concrete value
macro_rules! convertable_enum {
($enum_name: ident, $enum_type: ty, {$($name: ident = $value: expr,)+}) => {
enum $enum_name {
$($name = $value,)+
}
impl std::convert::TryFrom<$enum_type> for $enum_name {
type Error = String;
fn try_from(value: $enum_type) -> Result<Self, Self::Error> {
match value {
$($value => Ok($enum_name::$name), )+
_ => Err(format!("Unrecognized value {}", value)),
}
}
}
}
}
fn main() {
use std::convert::TryFrom;
convertable_enum!(Nums, i32, {One = 1, Two = 2,});
assert_eq!(Nums::One as i32, 1);
assert!(match Nums::try_from(2) {
Ok(Nums::Two) => true,
_ => false,
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment