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.

  4. If the enum has a strum(prefix = "some_value_"), every variant will have that prefix prepended to the serialization.

  5. Enums with fields support string interpolation. Note this means the variant will not “round trip” if you then deserialize the string.

    #[derive(strum_macros::Display)]
    pub enum Color {
        #[strum(to_string = "saturation is {sat}")]
        Red { sat: usize },
        #[strum(to_string = "hue is {1}, saturation is {0}")]
        Blue(usize, usize),
    }
// 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,
    #[strum(to_string = "purple with {sat} saturation")]
    Purple {
        sat: usize,
    },
}

// 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 }
);
// you can also use named fields in message
let purple = Color::Purple { sat: 10 };
assert_eq!(String::from("purple with 10 saturation"), purple.to_string());