Skip to content

Instantly share code, notes, and snippets.

@ishikawa
Created July 17, 2021 22:39
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 ishikawa/4a10ec8f2bde957a9638aa9679b2ec95 to your computer and use it in GitHub Desktop.
Save ishikawa/4a10ec8f2bde957a9638aa9679b2ec95 to your computer and use it in GitHub Desktop.
Rust: Converting between Enums and Strings
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