clap
clap (v4) builds typed CLIs with derive macros, shell completions, and helpful --help output. It is the standard for Rust command-line tools.
Busca en todas las páginas de la documentación
clap (v4) builds typed CLIs with derive macros, shell completions, and helpful --help output. It is the standard for Rust command-line tools.
[dependencies]
clap = { version = "4", features = ["derive"] }use clap::Parser;
#[derive(Parser, Debug)]
#[command(name = "ship", about = "Release helper")]
struct Cli {
/// Environment to deploy
#[arg(short, long, default_value = "staging")]
env: String,
/// Dry run only
#[arg(long)]
dry_run: bool,
}
fn main() {
let cli = Cli::parse();
println!("env={} dry_run={}", cli.env, cli.dry_run);
}When to reach for this:
use clap::{Parser, Subcommand};
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
cmd: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// List users
List { limit: u32 },
/// Create user
Create { email: String },
}
fn main() {
let cli = Cli::parse();
match cli.cmd {
Commands::List { limit } => println!("limit={limit}"),
Commands::Create { email } => println!("create {email}"),
}
}What this demonstrates:
--help text#[arg(long, env = "API_URL")]
api_url: String,Combine with figment or manual TOML for layered config.
use clap::Error;
// clap handles --help and misuse with exit code 2
// return `std::process::ExitCode` from main for app errors#[arg(long, alias = "old")].main, pass structs inward.default_value - required flags annoy local dev. Fix: sensible defaults plus env.display_order - related flags scatter. Fix: group with next_help_heading.| Alternative | Use When | Don't Use When |
|---|---|---|
argh | Minimal Google-style flags | Rich subcommands |
Manual std::env::args | One or two args | Anything users run daily |
bpaf | Functional combinator style | Team knows clap |
New projects use clap 4 derive API. Migration guides cover builder API changes.
clap_complete generates bash, zsh, fish scripts from your derive struct.
Call Cli::try_parse_from(["bin", "--env", "prod"]) in unit tests.
Use subcommands or multiple bin targets in Cargo.toml.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 16 jul 2026