Skip to content

Instantly share code, notes, and snippets.

Created September 7, 2016 08:05
Show Gist options
  • Save anonymous/c5610c31b8469422e57c23721cba09f8 to your computer and use it in GitHub Desktop.
Save anonymous/c5610c31b8469422e57c23721cba09f8 to your computer and use it in GitHub Desktop.

Revisions

  1. @invalid-email-address Anonymous created this gist Sep 7, 2016.
    47 changes: 47 additions & 0 deletions playground.rs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    macro_rules! enum_with_str_representation {
    (enum $enum_name:ident {
    $($variant:ident => $nice_name:expr,)+
    }) => {
    #[derive(Debug, PartialEq, Eq, Clone, Hash)]
    enum $enum_name {
    $($variant),+
    }

    impl ::std::fmt::Display for $enum_name {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
    match *self {
    $($enum_name::$variant => write!(f, $nice_name)),+
    }
    }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    struct ParseError;

    impl ::std::str::FromStr for $enum_name {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<$enum_name, Self::Err> {
    match s {
    $($nice_name => Ok($enum_name::$variant),)+
    _ => Err(ParseError),
    }
    }
    }
    }
    }

    enum_with_str_representation! {
    enum Status {
    Success => "Success",
    NoContent => "No content",
    NotFound => "Not found",
    }
    }

    fn main() {
    println!("{:?}", Status::Success);
    println!("{:?}", "Not found".parse::<Status>());
    println!("{:?}", "Internal Server Error".parse::<Status>());
    println!("{:?}", "Internal Server Error".parse::<Status>());
    }