expression

Clap Subcommand: dispatch separate operations

Subcommands group related operations with different input requirements. Match the parsed enum to choose behavior. This task-list model prints a planned add operation and performs no writes. Uses a fixed synthetic argument list or local data. Expected stdout (not executed): would add: Learn Rust Common mistake: Combining unrelated command inputs into a single struct full of optional fields.

Formal Syntax & Structure

rust syntaxrust
#[command(subcommand)] command: Operation

Working Example

Example Snippetrust
fn main() {    use clap::{Parser, Subcommand};    #[derive(Parser)]    struct Cli { #[command(subcommand)] command: Operation }    #[derive(Subcommand)]    enum Operation { Add { title: String }, List }    let cli = Cli::try_parse_from(["tasks", "add", "Learn Rust"]).unwrap();    match cli.command {        Operation::Add { title } => println!("would add: {title}"),        Operation::List => println!("would list tasks"),    }}
Rust Reference