Subcommands in Rust
One binary, several verbs: an enum of subcommands, each with its own args.
use clap::{Parser, Subcommand};
#[derive(Parser)]
struct Cli {
#[arg(long, global = true)]
quiet: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Play a tour step
Play { lang: String, idx: u32 },
/// Show your statistics
Stats {
#[arg(long, default_value = "week")]
window: String,
},
}
fn main() {
let cli = Cli::parse();
match cli.command {
Command::Play { lang, idx } => println!("playing {lang} step {idx}"),
Command::Stats { window } => println!("stats for the {window}"),
}
if !cli.quiet {
println!("done");
}
}
How it works
#[derive(Subcommand)]on an enum gives one variant per verb.- The parent struct holds the global flags.
- Matching on the enum dispatches the work.
Keywords and builtins used here
CliCommandStringboolenumfnifletmainmatchstructu32use
The run, in numbers
- Lines
- 32
- Characters to type
- 563
- Tokens
- 133
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 80 seconds.
Step 4 of 5 in Arguments, step 4 of 12 in CLI tools & HTTP clients.