We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie clap-guide

Clap Guide

[rust][cli][args]
Rust
Install
cargo add clap --features derive

Clap is the standard Rust library for CLI argument parsing. Derive API generates parser at compile time.

Supports subcommands, flags, positional args, env variable fallback, and shell completion.

The derive macro approach is preferred: annotate a struct and get full parser with --help for free.

Setup

Basic struct· Define CLI args.
use clap::Parser;

#[derive(Parser)]
#[command(name = "myapp")]
struct Cli {
    name: String,
    #[arg(short, long)]
    verbose: bool,
}

fn main() {
    let cli = Cli::parse();
    println!("Hello {}", cli.name);
}

Arguments

Optional flag· Short and long flags.
#[arg(short, long)]
verbose: bool

#[arg(short = 'o', long = "output")]
output: Option<PathBuf>
Default values· Default when not provided.
#[arg(short, long, default_value = "debug")]
log_level: String

#[arg(long, default_value_t = 8080)]
port: u16
Positional args· Required arguments.
#[derive(Parser)]
struct Cli {
    input_file: PathBuf,
    output_file: Option<PathBuf>,
}

Subcommands

Subcommands· Nested commands.
#[derive(Subcommand)]
enum Commands {
    Init { name: String },
    Push { remote: Option<String> },
    Status,
}

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

Validation

Validation· Validate argument values.
#[arg(short, long, value_parser = clap::value_parser!(u16).range(1..=65535))]
port: u16

#[arg(long, value_parser = |s: &str| -> Result<String, String> {
    if s.len() < 3 { Err("too short".into()) } else { Ok(s.into()) }
})]
name: String

Output

Help text· Custom help.
#[arg(short, long, help = "Set verbosity level")]
verbose: u8

#[command(about = "A fast tool for doing things", long_about = None)]