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.
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.
Frequently Asked Questions
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.
Citations (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
Related on TokRepo
Discussion
Related Assets
Moodle — Open-Source Learning Management System
The most widely used open-source learning platform, providing course management, assessments, and collaboration tools for educators and organizations worldwide.
Sylius — Headless E-Commerce Framework on Symfony
An open-source headless e-commerce platform built on Symfony and API Platform, designed for developers who need a customizable and API-first commerce solution.
Akaunting — Free Self-Hosted Accounting Software
A free, open-source online accounting application built on Laravel for small businesses and freelancers to manage invoices, expenses, and financial reports.