Say I have the following command line:
./app foo bar baz
I want to get this array out of it:
["foo", "bar", "baz"]
Is there a way to do this in clap, given that the positional arguments can be of arbitrary count?
The function you are looking for is values_of, you can use it like this:
let matches = App::new("My Super Program")
.arg(Arg::with_name("something")
.multiple(true))
.get_matches();
let iterator = matches.values_of("something");
for el in iterator.unwrap() {
println!("{:?}", el);
};
If you don't care about preserving invalid UTF-8 the easier choice is using values_of_lossy which returns an actual Vector (Option<Vec<String>>
) and not an iterator.
let arguments = matches.values_of_lossy("something").unwrap();
println!("{:?}", arguments);
Keep in mind that you really should not unwrap the values in your actual program as it will just crash at run-time if the arguments are not supplied. The only exception to this would be arguments that required(true)
was set on. Their absence would cause a run-time error (with helpful error messages) when calling get_matches
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With