Sub topic 16
The builder API and when to use it
This chapter assumes you can read the derive examples from earlier chapters, including #[derive(Parser)], #[arg(...)] attributes, and typed fields. It also assumes you know basic Rust ownership and Option.
What the builder API is
Derive is a layer on top of clap's builder API. The attributes you write expand into calls to Command and Arg. You can skip the derive layer and write those calls yourself. The result is the same parser, the same help output, and the same errors.
The main difference is how you read values. Derive gives you a struct with typed fields. The builder API gives you an ArgMatches value, and you look up each argument by its string id.
The same kind of CLI, built by hand
This program takes a required name and an optional --shout flag.
use clap::{Arg, ArgAction, Command};
fn main() {
let matches = 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")
.action(ArgAction::SetTrue)
.help("Print in upper case"),
)
.get_matches();
let name = matches.get_one::<String>("name").unwrap();
let greeting = format!("Hello, {name}!");
if matches.get_flag("shout") {
println!("{}", greeting.to_uppercase());
} else {
println!("{greeting}");
}
}Note the following points:
Arg::new("name")sets the id. With no.short()or.long(), the argument is positional.ArgAction::SetTruemakes--shouta flag.get_flagreturns abool.get_one::<String>("name")returnsOption<&String>. The type in the turbofish must match the argument's value type..unwrap()is safe here only because the argument isrequired(true). Clap rejects input without it before your code runs.
Where the builder API costs you
Ids are plain strings, so some mistakes move from compile time to run time:
- If you misspell an id in
get_one, clap panics when the code runs, not when it compiles. - If you ask for the wrong type, for example
get_one::<u16>on aStringargument, clap also panics. - Each value needs a manual
get_onecall, and there is no struct to pass around.
Debug builds check the definition for you. The debug_assert method used in the testing chapter works on a Command built this way too, so a test can catch these mistakes early.
Choosing between derive and builder
| Situation | Better choice |
|---|---|
| A fixed set of arguments known at compile time | Derive |
| You want typed fields and compile-time checks | Derive |
| Arguments are created at run time, such as from a config file or plugins | Builder |
| You need a clap feature that has no attribute form | Builder, or mix both |
| You want less macro expansion in compile times | Builder |
You do not have to pick only one. Cli::command() from CommandFactory returns a Command. You can adjust it with builder methods, such as adding an argument at run time, and then read the results from ArgMatches. The completions chapter used the same call to hand the derived definition to clap_complete.
For most tools, start with derive. Move to the builder API only when you hit one of the cases in the table.
Exercise
A tool's get_one::<u16>("port") call panics at run time even though the user passed --port 9000. The argument was declared as Arg::new("port").long("port"). What is the likely cause, and how would you fix it?
Show answer
The argument has no value parser, so clap treats its value as a String, and asking for u16 is a type mismatch that panics. Add .value_parser(clap::value_parser!(u16)) to the Arg, or read it with get_one::<String> and parse it yourself. A test that calls debug_assert and parses sample input would catch this before release.