Derive Macro strum::Display

source · []
#[derive(Display)]
{
    // Attributes available to this derive:
    #[strum]
}
Expand description

Converts enum variants to strings.

Deriving Display on an enum prints out the given enum. This enables you to perform round trip style conversions from enum into string and back again for unit style variants. Display choose which serialization to used based on the following criteria:

  1. If there is a to_string property, this value will be used. There can only be one per variant.
  2. Of the various serialize properties, the value with the longest length is chosen. If that behavior isn’t desired, you should use to_string.
  3. The name of the variant will be used if there are no serialize or to_string attributes.
// You need to bring the ToString trait into scope to use it
use std::string::ToString;
use strum_macros::Display;

#[derive(Display, Debug)]
enum Color {
    #[strum(serialize = "redred")]
    Red,
    Green {
        range: usize,
    },
    Blue(usize),
    Yellow,
}

// uses the serialize string for Display
let red = Color::Red;
assert_eq!(String::from("redred"), format!("{}", red));
// by default the variants Name
let yellow = Color::Yellow;
assert_eq!(String::from("Yellow"), yellow.to_string());
// or for string formatting
println!(
    "blue: {} green: {}",
    Color::Blue(10),
    Color::Green { range: 42 }
);