Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Repeat the same argument several times

  • Vec

  • required

  • If we set the element of the struct to be a vector then Clap will allow us to supply the same argument several times.

  • As a vector can also be emptty this will also work if we don't provide any --animal arguments.

  • We could also include required=true to require at least one value.

use clap::Parser;

#[derive(Parser, Debug)]
struct Cli {
    #[arg(long)]
    animal: Vec<String>,
}

fn main() {
    let args = Cli::parse();
    println!("{args:?}");
}
$ cargo run -q
Cli { animal: [] }

$ cargo run -q -- --animal Cat
Cli { animal: ["Cat"] }

$ cargo run -q -- --animal Cat Dog
error: unexpected argument 'Dog' found

Usage: repeat-the-same-argument [OPTIONS]

For more information, try '--help'.

$ cargo run -q -- --animal Cat --animal Dog
Cli { animal: ["Cat", "Dog"] }