Sub topic 3
Your first CLI with #[derive(Parser)]
This chapter assumes you can write basic Rust (structs, Option, Result) and use Cargo to build and run a project. You should also know what a command-line argument and a flag are. By the end you will have a working program whose arguments clap parses into a typed struct.
The idea: a struct is your CLI
With clap's derive API, you describe your command line as a struct. Each field is one argument. The field's type tells clap how to parse the text and whether the argument is required. Deriving Parser adds a parse() function that reads std::env::args, validates it, and returns your struct.
First, enable the derive feature in Cargo.toml:
[dependencies]
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4"Only derive is needed for this chapter. The other entries are used in later chapters.
A complete example
This program prints the parsed arguments. It takes a required file path, an optional filter, and a counted verbosity flag.
use clap::Parser;
use std::path::PathBuf;
/// Print lines of a file that contain a pattern.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
/// File to search
path: PathBuf,
/// Only print lines containing this text
#[arg(short, long)]
filter: Option<String>,
/// Increase output detail (-v, -vv)
#[arg(short, long, action = clap::ArgAction::Count)]
verbose: u8,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Run it with cargo run -- notes.txt -f todo -vv. The -- tells Cargo to pass everything after it to your program. The output is:
Cli { path: "notes.txt", filter: Some("todo"), verbose: 2 }How field types map to arguments
Clap reads each field and decides what kind of argument it is.
| Field | Meaning |
|---|---|
| `path: PathBuf` | Required positional argument |
| `filter: Option<String>` with `#[arg(short, long)]` | Optional `-f` / `--filter` that takes a value |
| `verbose: u8` with `ArgAction::Count` | Flag that counts repeats: `-v` gives 1, `-vv` gives 2 |
Two rules explain most of this behavior:
- A field with no
#[arg(...)]attribute is positional. Option<T>makes an argument optional. A plainTmakes it required.
The short and long options derive names from the field. The field filter becomes -f and --filter. Underscores in field names become hyphens, so dry_run becomes --dry-run.
Where help text comes from
Doc comments (///) on the struct and on each field become help text. In #[command(version, about)], version reads the version from Cargo.toml. about reuses the struct's doc comment. Run cargo run -- --help to see the result.
flowchart LRWhat happens when input is wrong
If the input does not match your struct, Cli::parse() prints a message and exits the process. Running with no path prints an error that names the missing argument and shows usage. Passing --help or --version also exits after printing. In both cases your code after parse() never runs. Chapter-level error control comes later, with try_parse.
Common mistakes
- Forgetting the
derivefeature. The compiler then reports that it cannot find theParserderive macro. - Forgetting
Debug. Printing with{cli:?}needs#[derive(Debug)]. - Using
cargo run notes.txtwithout--. Cargo may treat flags such as--helpas its own. - Expecting
u8to behave like a boolean. A plainboolfield is a flag with no value, whileu8withCountcounts occurrences.
Exercise
You add the field dry_run: bool with #[arg(long)]. What is the command-line name of the flag, and what value does the field have if the user does not pass it?
Show answer
The flag is --dry-run, because clap turns underscores into hyphens. A bool field is a flag that takes no value, so it is false when the flag is absent and true when present.