Search code examples
rustclap

Rust Clap Allow value from selected list


I have a variable

     #[clap(
        group = "abc",
        long = "attribute1",
        value_name = "ATTRIBUTE1"
    )]
    attribute1: Option<String>,

I want to enforce the users attribute1 can only provided a value from within an acceptable set of values?

acceptable_value = ["ABC", "QWERTY", "XYZ]

Can this be enforced as part of clap variable properties? or does this need to happen as part of logic execution later on in the code when using the variable?

Btw, using rust clap 3.2


Solution

  • I assume you're using 3.2.23.

    There are (AFAIK) two way (both requires you to create enum):

    1. derive clap::ValueEnum on the enum (seems prefered way, because the parser can show allowed values)
    2. alternatively, implement FromStr trait (you can use strum crate to reduce boilerplate)