Sub topic 16
The Builder API and When to Use It
This chapter assumes you have read the earlier chapters on #[derive(Parser)], Subcommand, and value_parser. It also assumes you are comfortable with Option, Result, and borrowing. The derive API is the right default. The builder API is what derive generates underneath, and you need to know it for the cases where derive does not fit.
How the two APIs relate
A #[derive(Parser)] struct does two jobs at compile time:
- It builds a
clap::Command, which is a description of your CLI (arguments, help text, constraints). - It implements
FromArgMatches, which copies parsed values from anArgMatchesinto your struct fields.
The builder API lets you do the first job by hand and read the second result yourself. You declare each argument with a string id and look it up in ArgMatches after parsing. Both APIs share the same parser, help formatter, and error messages. Output for equivalent definitions is nearly identical.
A builder program with a typed option
The spine example showed a minimal builder CLI. The version below adds a numeric option with range checking and a default, and wraps the definition in a function so tests can reuse it.
use clap::{value_parser, Arg, ArgAction, Command};
fn cli() -> Command {
Command::new("greet")
.version("1.0")
.about("Print a greeting")
.arg(Arg::new("name").required(true).help("Who to greet"))
.arg(
Arg::new("shout")
.long("shout")
.short('s')
.action(ArgAction::SetTrue)
.help("Print in upper case"),
)
.arg(
Arg::new("times")
.long("times")
.short('n')
.value_parser(value_parser!(u8).range(1..=10))
.default_value("1")
.help("How many times to print the greeting"),
)
}
fn main() {
let matches = cli().get_matches();
let name = matches.get_one::<String>("name").unwrap();
let times = *matches.get_one::<u8>("times").unwrap();
let greeting = format!("Hello, {name}!");
for _ in 0..times {
if matches.get_flag("shout") {
println!("{}", greeting.to_uppercase());
} else {
println!("{greeting}");
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn definition_is_valid() {
cli().debug_assert();
}
#[test]
fn rejects_zero_times() {
assert!(cli()
.try_get_matches_from(["greet", "Ada", "--times", "0"])
.is_err());
}
}Several points differ from derive:
- Ids are strings.
"name","shout", and"times"link the declaration to the lookup. Derive uses the field name for you. - Flags need an action.
ArgAction::SetTruemakes--shouta boolean flag. Without an action, clap treats the argument as taking a value. - Types are chosen twice.
value_parser!(u8)sets the type at declaration, andget_one::<u8>repeats it at lookup. If the two disagree,get_onepanics. - Defaults are strings.
default_value("1")goes through the same value parser as user input, so the default is checked too. unwrapis safe here.nameis required andtimeshas a default, soget_onealways returnsSome. For an optional argument without a default,get_onereturnsOption<&T>and you handleNone.
Subcommands and global arguments
The builder equivalent of a Subcommand enum is a list of nested Command values. You match on the subcommand name at runtime.
use clap::{Arg, ArgAction, Command};
fn cli() -> Command {
Command::new("tasks")
.about("A tiny task manager")
.subcommand_required(true)
.arg_required_else_help(true)
.arg(
Arg::new("verbose")
.long("verbose")
.global(true)
.action(ArgAction::SetTrue)
.help("Print extra detail for any subcommand"),
)
.subcommand(
Command::new("add")
.about("Add a task")
.arg(Arg::new("title").required(true)),
)
.subcommand(
Command::new("list").about("List tasks").arg(
Arg::new("all")
.short('a')
.long("all")
.action(ArgAction::SetTrue),
),
)
}
fn main() {
let matches = cli().get_matches();
let verbose = matches.get_flag("verbose");
match matches.subcommand() {
Some(("add", sub)) => {
let title = sub.get_one::<String>("title").unwrap();
println!("add {title:?} (verbose = {verbose})");
}
Some(("list", sub)) => {
println!("list (all = {}, verbose = {verbose})", sub.get_flag("all"));
}
_ => unreachable!("subcommand_required is set"),
}
}matches.subcommand() returns Option<(&str, &ArgMatches)>. Each subcommand gets its own ArgMatches, so its arguments are looked up on sub, not on matches. The compiler does not check that the name strings in match agree with the Command::new names. A typo falls through to the _ arm.
Failure modes of the builder API
The builder moves checks from compile time to run time. Know where each mistake surfaces:
| Mistake | What happens | How to catch it |
|---|---|---|
| Misspelled id in `get_one` | Panic at run time | `debug_assert` does not see lookups, so test the code path |
| Wrong type in `get_one::<T>` | Panic at run time | Test every lookup, or wrap lookups in one function |
| Two arguments with the same short name | Panic in debug builds | `cli().debug_assert()` in a test |
| `conflicts_with` naming a missing id | Panic in debug builds | `cli().debug_assert()` in a test |
| Forgetting `ArgAction::SetTrue` | The flag demands a value | Run `--help` and a smoke test |
Mixing derive and builder
You do not have to choose one API for the whole program. Every derived type exposes its Command through the CommandFactory trait, and FromArgMatches converts an ArgMatches back into the struct. This lets you adjust a derived CLI with builder methods.
use clap::{CommandFactory, FromArgMatches, Parser};
#[derive(Parser, Debug)]
struct Cli {
/// Port to listen on
#[arg(long, default_value_t = 8080)]
port: u16,
}
fn main() {
let cmd = Cli::command().after_help("Report bugs at https://example.com/issues");
let matches = cmd.get_matches();
let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
println!("{cli:?}");
}Error::exit prints the message and ends the process with clap's own exit code, the same as Cli::parse would. Methods like mut_arg and mut_subcommand also let you change one argument of a derived command without rewriting it.
When to use the builder API
Choose the builder API when the shape of the CLI is not known at compile time or does not map onto a struct:
- Arguments are generated at run time, for example from a plugin list or a config file. Owned
Stringids and help text need thestringfeature inCargo.toml. - The CLI wraps another tool and must mirror its options from data.
- You are writing a library that returns a
Commandfor others to embed. - You need an attribute that derive does not expose cleanly, and
mut_argis not enough.
Choose derive in all other cases. The reasons are concrete: the struct documents the CLI, field types replace the string-and-type pairing, a missing field is a compile error, and the code is shorter.
Exercise
In the builder program above, --times is declared with value_parser!(u8) but the code calls matches.get_one::<u16>("times"). What happens, and which test would reveal the mistake?
Show answer
get_one panics at run time because the stored value is a u8, not a u16. debug_assert() does not catch it. A test that parses valid arguments with try_get_matches_from and then performs the same lookup would panic and fail.
Exercise
You write Command::new("tasks").subcommand(Command::new("add")) and run tasks with no arguments. Why might the program reach your _ => unreachable!() arm, and which two Command methods prevent it?
Show answer
Subcommands are optional by default, so matches.subcommand() returns None when none is given. Calling subcommand_required(true) makes clap report an error instead. arg_required_else_help(true) prints the help text when no arguments are given.
Exercise
A teammate wants a CLI whose options come from a JSON file read at start-up. Which API fits, and what Cargo feature is likely needed?
Show answer
The builder API, because the arguments are not known at compile time. Owned String ids and help text need clap's string feature.