Clap CLI Argument Parsing

Parse CLI arguments with clap derive macros for type-safe command-line tools.

RustCli Tooling

Code

rustsnippet
25 lines
use clap::Parser;

#[derive(Parser, Debug)]
#[command(name = "app", version, about)]
struct Args {
    #[arg(short, long, default_value = "8080")]
    port: u16,
    #[arg(long, default_value = "localhost")]
    host: String,
    #[arg(long)]
    verbose: bool,
    #[command(subcommand)]
    command: Option<Command>,
}

#[derive(clap::Subcommand, Debug)]
enum Command {
    Serve,
    Build { output: String },
}

fn main() {
    let args = Args::parse();
    println!("{:?}", args);
}

What the code does

Clap CLI Argument Parsing is built around the function main.

What to watch for

  • Plan for an install step: clap::Parser is a real dependency, resolved by the package manager.

Applying it

Entry signature: fn main()

Statements that matter

let args = Args::parse();

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `clap::Parser`. Without it the snippet will not load.