Search code examples
rustclap

How to use clap to take create a vector


I have a basic struct like this

pub struct Args {
  #[clap(short, long, value_parser)]
  pub files: Vec<String>,
}

I'm trying to get this struct to take multiple values like such

cargo run -- --files hello world

But when I run this, it doesn't see world correctly. It errors with this:

error: Found argument 'world' which wasn't expected, or isn't valid in this context

What is the proper way to have clap populate this struct?


Solution

  • You can use num_args to specify a range for the number of argument occurences and values allowed like so:

    use clap::Parser;
    
    #[derive(Parser)]
    pub struct Args {
        #[clap(short, long, value_parser, num_args = 1.., value_delimiter = ' ')]
        pub files: Vec<String>,
      }
    
    fn main() {
        let args = Args::parse();
    
        println!("files: {:?}", args.files);
    }
    

    This will allow both

    cargo run -- --files hello world
    

    and

    cargo run -- --files hello --files world
    

    Specifying the value_delimiter is not strictly neccessary here, but I just wanted to point out that you can use different characters as delimiters like this.

    If you also want to allow empty arrays beeing passed, you can change the num_args attribute like so num_args = 0...