Derive Macro strum::EnumProperty

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

Add custom properties to enum variants.

Enables the encoding of arbitrary constants into enum variants. This method currently only supports adding additional string values. Other types of literals are still experimental in the rustc compiler. The generated code works by nesting match statements. The first match statement matches on the type of the enum, and the inner match statement matches on the name of the property requested. This design works well for enums with a small number of variants and properties, but scales linearly with the number of variants so may not be the best choice in all situations.


use strum_macros;
// bring the trait into scope
use strum::EnumProperty;

#[derive(strum_macros::EnumProperty, Debug)]
#[allow(dead_code)]
enum Color {
    #[strum(props(Red = "255", Blue = "255", Green = "255"))]
    White,
    #[strum(props(Red = "0", Blue = "0", Green = "0"))]
    Black,
    #[strum(props(Red = "0", Blue = "255", Green = "0"))]
    Blue,
    #[strum(props(Red = "255", Blue = "0", Green = "0"))]
    Red,
    #[strum(props(Red = "0", Blue = "0", Green = "255"))]
    Green,
}

let my_color = Color::Red;
let display = format!(
    "My color is {:?}. It's RGB is {},{},{}",
    my_color,
    my_color.get_str("Red").unwrap(),
    my_color.get_str("Green").unwrap(),
    my_color.get_str("Blue").unwrap()
);
assert_eq!("My color is Red. It\'s RGB is 255,0,0", &display);