Derive Macro strum::EnumMessage

source ยท
#[derive(EnumMessage)]
{
    // Attributes available to this derive:
    #[strum]
}
Expand description

Add a verbose message to an enum variant.

Encode strings into the enum itself. The strum_macros::EmumMessage 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 separate more detailed message than the first.

EnumMessage also exposes the variants doc comments through get_documentation(). This is useful in some scenarios, but get_message should generally be preferred. Rust doc comments are intended for developer facing documentation, not end user messaging.

// You need to bring the trait into scope to use it
use strum::EnumMessage;
use strum_macros;

#[derive(strum_macros::EnumMessage, Debug)]
#[allow(dead_code)]
enum Color {
    /// Danger 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 looks like more or less like this:
/*
impl ::strum::EnumMessage for Color {
    fn get_message(&self) -> ::core::option::Option<&'static str> {
        match self {
            &Color::Red => ::core::option::Option::Some("Red"),
            &Color::Green {..} => ::core::option::Option::Some("Simply Green"),
            _ => None
        }
    }

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

    fn get_documentation(&self) -> ::std::option::Option<&'static str> {
        match self {
            &Color::Red => ::std::option::Option::Some("Danger color."),
            _ => None
        }
    }

    fn get_serializations(&self) -> &'static [&'static 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
            },
        }
    }
}
*/

let c = Color::Red;
assert_eq!("Red", c.get_message().unwrap());
assert_eq!("This is very red", c.get_detailed_message().unwrap());
assert_eq!("Danger color.", c.get_documentation().unwrap());
assert_eq!(["Red"], c.get_serializations());