clap
Derive-based argument parsing with validation, help generation, and subcommands.
Busca en todas las páginas de la documentación
Derive-based argument parsing with validation, help generation, and subcommands.
use clap::Parser;
#[derive(Parser)]
#[command(name = "greet", version, about = "Greet someone")]
struct Args {
/// Name to greet
name: String,
/// Number of times to greet
#[arg(short, long, default_value_t = 1)]
count: u8,
}
fn main() {
let args = Args::parse();
for _ in 0..args.count {
println!("Hello, {}!", args.name);
}
}When to reach for this: Any CLI with more than one or two flags. clap is the de facto standard in the Rust ecosystem.
use clap::{Parser, Subcommand, ValueEnum};
use std::path::PathBuf;
#[derive(Parser)]
#[command(name = "backup", version, about = "Backup files")]
struct Cli {
/// Increase verbosity (-v, -vv)
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
/// Config file path
#[arg(short, long, env = "BACKUP_CONFIG")]
config: Option<PathBuf>,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand)]
enum Command {
/// Create a new backup
Create {
#[arg(value_enum)]
format: Format,
source: PathBuf,
},
/// List existing backups
List,
}
#[derive(Clone, ValueEnum)]
enum Format {
Tar,
Zip,
}
fn main() -> anyhow::Result<()> {
let cli = Cli::parse();
match cli.command {
Command::Create { format, source } => {
println!("backing up {source:?} as {format:?}");
}
Command::List => println!("no backups yet"),
}
Ok(())
}What this demonstrates:
--help and validation automaticallyenv = binds environment variables to flagsValueEnum restricts choices to a typed set#[derive(Parser)] expands to a parse() implementation at compile timeArgAction::Count implements -v / -vv verbosity patterns| Attribute | Purpose |
|---|---|
short, long | -n and --name flags |
default_value_t | Default when flag omitted |
required = true | Fail if argument missing |
conflicts_with | Mutually exclusive flags |
requires | Dependent flag groups |
Use the builder API when you need dynamic arguments at runtime.
use clap::{Arg, Command};
let cmd = Command::new("dynamic")
.arg(Arg::new("file").required(true));
let matches = cmd.get_matches();derive feature - Add clap = { version = "4", features = ["derive"] }. Fix: Enable the derive feature in Cargo.toml.Subcommand derive - Plain enums fail to compile. Fix: Add #[derive(Subcommand)].default_value vs default_value_t - String defaults need quotes; typed defaults use _t. Fix: Match the attribute to your field type.#[command(flatten)] merges args but can cause name collisions. Fix: Use unique field names or explicit id.#[command(version = env!("CARGO_PKG_VERSION"))].| Alternative | Use When | Don't Use When |
|---|---|---|
argh | Minimal binary size, Google-style flags | You need rich subcommands |
pico-args | Tiny dependency footprint | Complex validation rules |
Manual std::env::args | Learning or throwaway scripts | Production tools with --help |
clap 4 is the current stable API. New projects should use clap 4 with derive macros.
Add #[command(subcommand_required = true)] on the root Parser struct.
Yes. Use Args::parse_from(["prog", "--flag", "value"]) in tests.
Use #[arg(hide = true)] on the field.
Place flags on the root struct. They apply to all subcommands automatically.
Use value_parser = clap::value_parser!(PathBuf) plus a custom validator, or check in main after parsing.
Use clap_complete crate. See the shell completions page.
Call parse_from with synthetic argv in unit tests. Assert on Err for invalid input.
Defaults appear automatically when you set default_value or default_value_t.
Use #[command(about = "...")] or long_about for extended descriptions.
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: 19 jul 2026