Say I have a structopt argument:
#[structopt(name = "foos")]
foos: Vec<String>,
I can't seem to find a way to pass a requirement to clap saying that _at least_ one value is required, and running the app without passing any values is considered a successful run.
How can I make it mandatory to pass at least one value to foos?
you want https://docs.rs/clap/2.31.1/clap/struct.Arg.html#method.required so something like that:
#[derive(StructOpt, Debug)]
struct Opt {
#[structopt(raw(required = "true"))]
foos: Vec<String>,
}
You might also be interested by https://docs.rs/clap/2.31.1/clap/struct.Arg.html#method.min_values you can find a complete example at https://github.com/TeXitoi/structopt/blob/master/examples/at_least_two.rs
Does it answer your question?
Yes, that works well, thank you. 馃憤
For anyone coming across this in future, I believe the correct way to do it now is
#[derive(StructOpt, Debug)]
struct Opt {
#[structopt(required = true)]
foos: Vec<String>,
}
To add to @clbarnes update, if you're searching for a way to require a "minimum number of entries" as the title suggested, then you can use min_values = ....
#[derive(StructOpt, Debug)]
struct Opt {
// #[structopt(required = true, min_values = 2)]
// same as
#[structopt(min_values = 2)]
foos: Vec<String>,
}
If min_values is used, then required is implied. However specifying both is perfectly valid.
To add to @clbarnes update, if you're searching for a way to require a "minimum number of entries" as the title suggested, then you can use
min_values = ....#[derive(StructOpt, Debug)] struct Opt { // #[structopt(required = true, min_values = 2)] // same as #[structopt(min_values = 2)] foos: Vec<String>, }If
min_valuesis used, thenrequiredis implied. However specifying both is perfectly valid.
I tried to use only min_values, it still runs successfully when the arg is NOT specified. In this case we do need specify required = true explicitly.
Most helpful comment
For anyone coming across this in future, I believe the correct way to do it now is