Created
July 17, 2021 22:39
-
-
Save ishikawa/4a10ec8f2bde957a9638aa9679b2ec95 to your computer and use it in GitHub Desktop.
Rust: Converting between Enums and Strings
This file contains hidden or 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
pub enum Foo { | |
A, | |
B, | |
} | |
impl Foo { | |
pub fn variants() -> impl Iterator<Item = Foo> { | |
array::IntoIter::new([Self::A, Self::B]) | |
} | |
} | |
impl fmt::Display for Foo { | |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
match self { | |
Foo::A => write!(f, "a"), | |
Foo::B => write!(f, "b"), | |
} | |
} | |
} | |
impl FromStr for Foo { | |
type Err = String; | |
fn from_str(s: &str) -> Result<Self, Self::Err> { | |
Self::variants() | |
.find(|x| x.to_string() == s) | |
.ok_or_else(|| format!("Unknown option: `{}`", s)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment