Last active
December 31, 2019 09:23
-
-
Save internetimagery/a2fd6da5127676c05a8f12dc1deb132f to your computer and use it in GitHub Desktop.
Enum to and from concrete value
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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