typestar

Flags, counts and lists in Rust

Optional values, repeated flags, and arguments that take many values.

use clap::{ArgAction, Parser};

#[derive(Parser, Debug)]
struct Cli {
    /// Tours to include
    #[arg(short, long)]
    tour: Vec<String>,

    /// Write results here
    #[arg(short, long)]
    out: Option<String>,

    /// Repeat for more detail
    #[arg(short, long, action = ArgAction::Count)]
    verbose: u8,

    /// Skip the confirmation
    #[arg(long, default_value_t = false)]
    force: bool,
}

fn main() {
    let cli = Cli::parse();
    println!("{:?} -> {:?}", cli.tour, cli.out);
    println!("verbosity {} force {}", cli.verbose, cli.force);
}

How it works

  1. Option<T> makes an argument optional.
  2. ArgAction::Count turns -v -v into a level.
  3. A Vec<T> field collects every occurrence.

Keywords and builtins used here

The run, in numbers

Lines
26
Characters to type
505
Tokens
100
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 60 seconds.

Type this snippet

Step 3 of 5 in Arguments, step 3 of 12 in CLI tools & HTTP clients.

← Previous Next →