Sub topic 3
Your first CLI with #[derive(Parser)]
This chapter assumes you know basic Rust (structs, Option, Result, ownership), can create and run a Cargo project, and have used command-line programs with flags and exit codes. It builds on the previous chapter, where you added clap to Cargo.toml with the derive feature. Here you define a CLI as a struct and let clap turn the command line into typed fields.
The idea: a struct is the interface
With the derive API, you describe your command line as a plain Rust struct. Each field is one argument. The field's type tells clap how to parse it and whether it is required. The #[derive(Parser)] macro generates the code that reads std::env::args, validates the input, and builds the struct.
This is the full program from the plan for this chapter:
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:?}");
}Three things in this file do the work:
#[derive(Parser)]generates theCli::parse()method and the code behind it.#[command(...)]configures the whole command, such as its version and description.#[arg(...)]on a field configures that one argument.
Debug is derived only so that main can print the result with {cli:?}. clap does not require it.
How field types become argument rules
clap reads the shape of each field and decides how the argument behaves.
| Field | Declaration | Behavior |
|---|---|---|
| `path` | `PathBuf` with no `#[arg]` | Positional argument, required |
| `filter` | `Option<String>` with `short, long` | Option that takes a value, may be omitted |
| `verbose` | `u8` with `ArgAction::Count` | Flag whose occurrences are counted |
A field with no #[arg] attribute becomes a positional argument, identified by its place on the command line. Wrapping the type in Option<T> makes the argument optional. Without Option, a missing argument is an error and clap exits before your code runs.
The field name also becomes the argument's name. A field called filter with long gives you --filter. Underscores in a field name turn into hyphens, so dry_run becomes --dry-run.
Running it
Build and run the program, passing arguments after -- so Cargo does not interpret them itself.
cargo run -- notes.txt
cargo run -- notes.txt --filter todo
cargo run -- notes.txt -f todo -vvThe first command prints something like this:
Cli { path: "notes.txt", filter: None, verbose: 0 }The third prints Cli { path: "notes.txt", filter: Some("todo"), verbose: 2 }. The short flags -f and -v come from short, which takes the first letter of the field name. Because verbose is a counted flag, -vv gives 2, and you can also write -v -v.
Doc comments become help text
A /// comment on the struct becomes the command's description. A /// comment on a field becomes that argument's help line. You get this output for free:
cargo run -- --helpPrint lines of a file that contain a pattern
Usage: app [OPTIONS] <PATH>
Arguments:
<PATH> File to search
Options:
-f, --filter <FILTER> Only print lines containing this text
-v, --verbose... Increase output detail (-v, -vv)
-h, --help Print help
-V, --version Print versionThe program name in the Usage line comes from your package name. clap adds -h and -V itself.
#[command(version, about)] with no values tells clap to read them from Cargo.toml. version uses the version field, and about uses the package description (or, for a struct with a doc comment, the doc comment text). Because version is set, --version works without more code.
What happens when input is wrong
Cli::parse() handles bad input for you. If you leave out the path, clap prints an error and exits with code 2 without returning to main:
error: the following required arguments were not provided:
<PATH>
Usage: app [OPTIONS] <PATH>
For more information, try '--help'.The same applies to an unknown flag or a missing value after --filter. Requests for --help and --version also exit from inside parse(), but with code 0 and output on stdout.
So the rule is simple. If Cli::parse() returns, you hold a valid Cli. You do not re-check that path exists as an argument, because the type guarantees it. (Whether the file exists on disk is a different question, and clap does not check that.)
If you need to handle parse errors yourself, use Cli::try_parse(), which returns a Result. Later chapters cover this in the error handling and testing sections.
The parse flow
The diagram shows where clap sits between the operating system and your code.
Common mistakes
- Forgetting the
derivefeature. Withoutfeatures = ["derive"]inCargo.toml,use clap::Parsercompiles but#[derive(Parser)]fails with an unresolved derive macro error. - Forgetting
use clap::Parser. Theparse()method comes from theParsertrait. Without the import,Cli::parse()reports that the function is not found. - Using
boolfor something that needs a value. Aboolfield with#[arg(long)]is a flag that is true when present. If you want--name value, useStringorOption<String>. - Expecting
u8to mean a number you type. Au8field with no action is parsed as a number. TheCountaction is what makes it count repeated flags, so both pieces are needed here. - Passing arguments without
--tocargo run. Cargo would take flags like--helpfor itself. Put--before your own arguments. - Treating a field name as free. Renaming a field changes the long option name, which is a change to your public interface.
Optional: where the field name shows up
Rename the filter field to pattern and rerun --help. The option becomes --pattern <PATTERN> and the short flag becomes -p. The long and short names, the value placeholder, and the struct field all change together, which is why a rename is a visible change for users.
Exercise
A struct has the fields input: PathBuf, output: Option<PathBuf> with #[arg(short, long)], and dry_run: bool with #[arg(long)]. Which of these must the user supply, what are the option spellings, and what happens when input is missing?
Show answer
Only input is required, because it is a positional argument whose type is not Option. The options are -o and --output <OUTPUT> for the output path, and --dry-run (underscore becomes hyphen) for the flag, which has no short form because short was not requested. If input is missing, Cli::parse() prints an error to stderr that lists <INPUT> as a missing required argument and exits with code 2 before main continues.
Exercise
You run cargo run -- notes.txt -vvv against the program in this chapter. What value does verbose hold, and which attribute makes that happen?
Show answer
verbose holds 3. The action = clap::ArgAction::Count setting in #[arg(...)] makes clap increase the u8 field once for each occurrence of the flag, and -vvv is three occurrences written together.