Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust Clap Allow value from selected list

Tags:

rust

clap

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

like image 985
alwaysAStudent Avatar asked Apr 10 '26 18:04

alwaysAStudent


1 Answers

I assume you're using 3.2.23.

There are at least two way. Both way requires you to create enum:

  1. derive clap::ValueEnum on the enum (seems prefered way, because the parser can show or suggest from allowed values)
  2. alternatively, implement FromStr trait (you can use strum crate to reduce boilerplate)
like image 57
user-id-14900042 Avatar answered Apr 13 '26 10:04

user-id-14900042