Skip to main content

#
03_04_subcommands_derive/
03_04_subcommands.rs

    1use clap::{Parser, Subcommand};
    2
    3#[derive(Parser)]
    4#[command(version, about, long_about = None)]
    5#[command(propagate_version = true)]
    6struct Cli {
    7    #[command(subcommand)]
    8    command: Commands,
    9}
    10
    11#[derive(Subcommand)]
    12enum Commands {
    13    /// Adds files to myapp
    14    Add { name: Option<String> },
    15}
    16
    17fn main() {
    18    let cli = Cli::parse();
    19
    20    // You can check for the existence of subcommands, and if found use their
    21    // matches just as you would the top level cmd
    22    match &cli.command {
    23        Commands::Add { name } => {
    24            println!("'myapp add' was used, name is: {name:?}");
    25        }
    26    }
    27}