Skip to content

Derive Display

Peter Glotfelty edited this page Aug 18, 2019 · 1 revision

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 type into scope to use it!!!
use std::string::ToString;

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

// It's simple to iterate over the variants of an enum.
fn debug_colors() {
    let red = Color::Red;
    assert_eq!(String::from("redred"), red.to_string());
}

fn main() {
    debug_colors();
}
Clone this wiki locally