tshepang
tshepang

Reputation: 12459

Iterate through positional arguments with 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?

Upvotes: 14

Views: 7015

Answers (1)

H2O
H2O

Reputation: 662

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.

Upvotes: 12

Related Questions