-
Notifications
You must be signed in to change notification settings - Fork 151
Derive EnumProperty
Peter Glotfelty edited this page Aug 18, 2019
·
1 revision
Enables the encoding of arbitary 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.
Here's an example:
# extern crate strum;
# #[macro_use] extern crate strum_macros;
# use std::fmt::Debug;
// You need to bring the type into scope to use it!!!
use strum::EnumProperty;
#[derive(EnumProperty,Debug)]
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,
}
fn main() {
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());
}