Clap — Command Line Argument Parser for Rust
Clap is the most popular CLI argument parser for Rust. It provides derive macros for declarative argument definitions, rich help generation, shell completions, subcommands, and comprehensive validation — the Rust equivalent of Python argparse on steroids.
Installation agent prête
Cet actif peut être installé après choix du runtime, vérification du plan et exécution de la commande adaptée.
npx -y tokrepo@latest install 8256d544-3745-11f1-9bc6-00163e2b0d79 --target codexÀ exécuter après confirmation du plan en dry-run.
What it is
Clap is the most widely used CLI argument parser for Rust. It offers two styles: a derive macro approach where you annotate a struct with argument definitions, and a builder API for dynamic or complex argument trees. Clap handles help text generation, shell completions, subcommands, argument groups, value validation, and error formatting.
Clap is the Rust equivalent of Python argparse but with compile-time validation and significantly richer features. It suits anyone building command-line tools in Rust, from simple scripts to complex multi-subcommand applications like cargo itself.
How it saves time or tokens
Without Clap, you parse std::env::args manually, write your own help text, handle missing or invalid values, and build shell completion scripts by hand. Clap generates all of this from your struct definition. A CLI with ten flags, three subcommands, and bash/zsh/fish completions takes minutes to define instead of hours.
How to use
- Add Clap with derive support:
cargo add clap --features derive. - Define a struct annotated with
#[derive(Parser)]and use#[arg(...)]attributes for each field. - Call
Cli::parse()in main -- Clap reads arguments, validates them, and returns a populated struct.
Example
use clap::Parser;
#[derive(Parser)]
#[command(name = 'myapp', about = 'A sample CLI application')]
struct Cli {
/// Name of the person to greet
#[arg(short, long)]
name: String,
/// Number of times to greet
#[arg(short, long, default_value_t = 1)]
count: u8,
}
fn main() {
let cli = Cli::parse();
for _ in 0..cli.count {
println!('Hello {}!', cli.name);
}
}
$ cargo run -- --name Alice --count 3
Hello Alice!
Hello Alice!
Hello Alice!
Related on TokRepo
- Automation Tools -- CLI utilities and build tools
- Coding Tools -- Developer productivity libraries
Common pitfalls
- Forgetting the
derivefeature flag results in cryptic compile errors since theParserderive macro is feature-gated. - Using
Stringfor optional arguments without wrapping inOption<String>makes Clap require the argument, which confuses users who expect it to be optional. - Not specifying
value_parserfor custom types leads to unhelpful error messages when validation fails.
Questions fréquentes
The derive API uses Rust attributes on a struct to declare arguments -- concise and type-safe. The builder API constructs argument definitions programmatically at runtime, useful when arguments depend on configuration or plugins. Most projects use derive because it catches errors at compile time and generates less boilerplate.
Yes. The clap_complete crate generates completion scripts for bash, zsh, fish, PowerShell, and elvish. You add a hidden subcommand that outputs the completion script, or generate it at build time and ship it with your binary.
Define an enum with `#[derive(Subcommand)]` where each variant represents a subcommand with its own argument struct. Clap routes the user input to the correct variant and parses its arguments independently. Nested subcommands are supported by nesting enums.
Yes. Use `#[arg(env = 'MY_VAR')]` and Clap reads the environment variable if the user does not provide the argument on the command line. The help text automatically shows the env var name. This is useful for container deployments where config comes from the environment.
Structopt was a popular derive layer on top of Clap 2. Starting with Clap 3, the derive functionality was merged into Clap itself, making structopt unnecessary. If you were using structopt, migrate to `clap::Parser` with minimal changes.
Sources citées (3)
- Clap GitHub— Clap is the most popular argument parser for Rust
- Clap Documentation— Supports derive and builder APIs for argument definition
- clap_complete Docs— Shell completions via clap_complete for bash, zsh, fish, and PowerShell
En lien sur TokRepo
Fil de discussion
Actifs similaires
Hyperfine — Command-Line Benchmarking Tool
Hyperfine is a command-line benchmarking tool written in Rust. Run benchmarks with statistical analysis: multiple runs, warmup, outlier detection, comparison across commands, and export results. By the author of bat and fd.
jq — Lightweight Command-Line JSON Processor
jq is the essential command-line tool for processing JSON data. It lets you slice, filter, transform, and format JSON with a concise expression language — making it indispensable for working with APIs, config files, and data pipelines in the terminal.
Cookiecutter — Project Templates from the Command Line
A command-line utility that creates projects from cookiecutter templates, supporting Python, JavaScript, Ruby, and any other language or framework with Jinja2 templating.
Scoop — Command-Line Installer for Windows Developer Tools
Scoop is a command-line installer for Windows that focuses on developer tools. It installs programs to your home directory by default, avoids UAC pop-ups, and keeps your PATH clean by shimming executables automatically.