How to Create a Multi-Command CLI Tool in Rust

Cli
Create a multi-command CLI in Rust by defining a struct with subcommands using the clap crate and matching on the parsed arguments.

Use the clap crate to define a Command struct with subcommands, then parse arguments in main using ArgMatches to route logic.

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "my-cli")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Add { name: String },
    Remove { id: u32 },
}

fn main() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Add { name } => println!("Adding: {}", name),
        Commands::Remove { id } => println!("Removing ID: {}", id),
    }
}

Add clap = { version = "4", features = ["derive"] } to your Cargo.toml dependencies.