12

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?

tshepang
  • 12,111
  • 21
  • 91
  • 136

1 Answers1

12

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.

H2O
  • 612
  • 8
  • 18
  • The unwrap is ok if we got `required(true)`, right? – tshepang May 21 '17 at 10:14
  • Yes, when the argument is required you get a runtime error when calling `get_matches`. So the value not being present could only happen due to a programmer error in which case crashing would be reasonable. – H2O May 21 '17 at 11:18
  • 2
    @EliazBobadilla: If you're gonna edit the code to match clap 3, you should probably also adjust the links to doc.rs. But I think having both versions of the code around would be good. Maybe post a separate answer? – Caesar Apr 06 '22 at 03:54
  • FWIW, Right now I'd love to see a separate answer for the clap 3 derive syntax. – lamont Apr 01 '23 at 21:20