macro_rules! define_str_enum {
    (
        $(#![$macro_attr:ident])?
        $(#[$emeta:meta])*
        $vis:vis enum $enum:ident {
            $(
                $(#[$varmeta:meta])*
                $variant:ident = $display:literal $(= $num:literal)?,
            )+
        }
    ) => { ... };
    (@attr coerce_from_str $($then:tt)*) => { ... };
    (@attr $other:ident $($then:tt)*) => { ... };
}
Expand description

Auto-generate enum that maps to a string.

It automatically derives/implements the following traits:

Example

define_str_enum! {
    pub enum Color {
        Red = "#FF0000",
        Green = "#00FF00",
        Blue = "#0000FF",
    }
}

This macro expands into something like this:

pub enum Color {
    Red,
    Green,
    Blue,
}

impl Color {
    pub const VARIANTS: &[Self] = &[Self::Red, Self::Green, Self::Blue];

    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Red => "#FF0000",
            Self::Green => "#00FF00",
            Self::Blue => "#0000FF",
        }
    }

    // ... for full list see the implementation.
}

Implicit string coercion

#![coerce_from_str]

By default, generated enums are case-sensitive.

This inner attribute enables implicit string coercion when enum is constructed using FromStr trait: the string is trimmed and converted to lower case before matching.

Note, that in that case string variants must be specified in lower case too.

define_str_enum! {
    #![coerce_from_str]
    pub enum Season {
        Summer = "summer",
    }
}

use std::str::FromStr;
assert_eq!(Season::from_str("summer"), Ok(Season::Summer));
assert_eq!(Season::from_str("SummeR"), Ok(Season::Summer));
assert_eq!(Season::from_str("  SUMMER  "), Ok(Season::Summer));