clap
Command line argument parser for Rust with derive macros, validation, and generated help texts.
Official Documentation ↗v4. Check the official docs for the latest API surface.Installation
cargo add clap --features deriveMethods
No methods match this filter.
Command line argument parser for Rust with derive macros, validation, and generated help texts.
Overview
clap parses command lines from declarative structs. With the derive feature, fields and doc comments become typed options with validation, defaults, and generated help; an enum of subcommands structures multi-verb tools. Parse failures exit with helpful errors before main logic runs.
The builder API constructs the same command trees dynamically when arguments are not known at compile time. Completion scripts, version flags, and environment fallbacks are built in, making clap the standard CLI layer for Rust tools.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
#[derive(Parser)]— Derives the parser from a struct; fields become options with types as validation.Subcommand— Declares subcommands as an enum with their own argument fields.builder API— Runtime construction of commands and args when the structure is dynamic.try_parse / errors— Parses without terminating on error, for embedding CLIs inside larger programs.
Usage Notes
- Doc comments become help text; write them for users, not for reviewers.
- Use value_parser for enums to reject invalid values with clear messages.
- try_parse lets you embed argument handling without owning the process exit.
Common Pitfalls
- Forgetting the derive feature makes the macros unavailable even though the crate compiles.
- String fields accept anything; stronger types, u16, PathBuf, enums, catch bad input at parse time.
- Panicking on unwrap of matches defeats clap error handling; prefer derived structs.
FAQ
- Derive or builder API?
- Derive keeps declarations next to types and is the idiomatic choice for static CLIs. Builder constructs commands at runtime, which suits generated commands or plugins. Both share the same underlying engine and help generation.
- How do defaults and required interact?
- A field with default_value_t is optional on the command line but never None in the struct. Required means the user must supply it unless a default exists; Option<T> fields surface as None when omitted instead.
- What happened between clap 3 and 4?
- v4 renamed APIs, Arg::with_name to Arg::new, moved to Vec-based values, and improved error formatting. Migration is mostly mechanical via the migration guide, but pinned dependencies in tools deserve a deliberate upgrade.
Report a problem with this API docOpens a pre-filled issue on GitHub.