Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through positional arguments with clap

Tags:

rust

clap

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?

like image 257
tshepang Avatar asked May 21 '17 07:05

tshepang


1 Answers

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.

like image 132
H2O Avatar answered Sep 22 '22 22:09

H2O