Skip to content

Derive EnumMessage

Peter Glotfelty edited this page Aug 18, 2019 · 1 revision

Encode strings into the enum itself. This macro implements the strum::EnumMessage trait. EnumMessage looks for #[strum(message="...")] attributes on your variants. You can also provided a detailed_message="..." attribute to create a seperate more detailed message than the first.

The generated code will look something like:

// You need to bring the type into scope to use it!!!
use strum::EnumMessage;

#[derive(EnumMessage,Debug)]
enum Color {
    #[strum(message="Red",detailed_message="This is very red")]
    Red,
    #[strum(message="Simply Green")]
    Green { range:usize },
    #[strum(serialize="b",serialize="blue")]
    Blue(usize),
}

/*
// Generated code
impl ::strum::EnumMessage for Color {
    fn get_message(&self) -> ::std::option::Option<&str> {
        match self {
            &Color::Red => ::std::option::Option::Some("Red"),
            &Color::Green {..} => ::std::option::Option::Some("Simply Green"),
            _ => None
        }
    }

    fn get_detailed_message(&self) -> ::std::option::Option<&str> {
        match self {
            &Color::Red => ::std::option::Option::Some("This is very red"),
            &Color::Green {..}=> ::std::option::Option::Some("Simply Green"),
            _ => None
        }
    }

    fn get_serializations(&self) -> &[&str] {
        match self {
            &Color::Red => {
                static ARR: [&'static str; 1] = ["Red"];
                &ARR
            },
            &Color::Green {..}=> {
                static ARR: [&'static str; 1] = ["Green"];
                &ARR
            },
            &Color::Blue (..) => {
                static ARR: [&'static str; 2] = ["b", "blue"];
                &ARR
            },
        }
    }
}
*/
Clone this wiki locally