Rust

clap — Derive-Style CLI Parser

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`clap` with the derive macro turns a Rust struct into a fully-featured CLI: `--help`, `--version`, validation, subcommands. The most popular CLI framework in the Rust ecosystem.
Rust
Raw
// Cargo.toml: clap = { version = "4", features = ["derive"] }
use clap::{Parser, Subcommand};

#[derive(Parser, Debug)]
#[command(name = "myapp", version, about = "Does a useful thing", long_about = None)]
struct Cli {
    /// Verbose output (-v, -vv, -vvv)
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,

    /// Configuration file
    #[arg(short, long, default_value = "config.toml")]
    config: String,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand, Debug)]
enum Command {
    /// Initialize a new project
    Init { path: String },
    /// Run the server
    Run {
        #[arg(short, long, default_value_t = 8080)]
        port: u16,
        #[arg(long)]
        debug: bool,
    },
}

fn main() {
    let cli = Cli::parse();
    println!("config: {}  verbose level: {}", cli.config, cli.verbose);
    match cli.command {
        Command::Init { path }        => println!("initializing in {path}"),
        Command::Run  { port, debug } => println!("server on :{port} (debug={debug})"),
    }
}
// Run: cargo run -- run --port 3000 --debug -vv
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.