Skip to content

Derive EnumVariantNames

Peter Glotfelty edited this page Dec 20, 2019 · 2 revisions

Adds an impl block for the enum that adds a static variants() method that returns an array of &'static str that are the discriminant names. This will respect the serialize_all attribute on the enum (like #[strum(serialize_all = "snake_case")], see Additional Attributes below).

Note: This is compatible with the format clap expects for enums, meaning this works:

use strum::{EnumString, EnumVariantNames};
// You need to import the trait.
use strum::VariantNames;

#[derive(EnumString, EnumVariantNames)]
#[strum(serialize_all = "kebab_case")]
enum Color {
    Red,
    Blue,
    Yellow,
    RebeccaPurple,
}

fn main() {
    // This is what you get:
    assert_eq!(
        &Color::VARIANTS,
        &["red", "blue", "yellow", "rebecca-purple"]
    );
    
    // Use it with clap like this:
    let args = clap::App::new("app")
        .arg(Arg::with_name("color")
            .long("color")
            .possible_values(&Color::VARIANTS)
            .case_insensitive(true))
        .get_matches();

    // ...
}

This also works with structopt (assuming the same definition of Color as above):

#[derive(Debug, StructOpt)]
struct Cli {
    /// The main color
    #[structopt(long = "color", default_value = "Color::Blue", raw(possible_values = "&Color::variants()"))]
    color: Color,
}