How to Add Subcommands to a Rust CLI with clap

Add subcommands to a Rust CLI by defining a Subcommand enum and matching on the parsed result.

You add subcommands by defining a Command with subcommand() and matching on the parsed result in main.

use clap::{Parser, Subcommand};

#[derive(Parser)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

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

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