Sub topic 4
Positional arguments
This chapter assumes you can write a basic Rust struct, use Option and Vec, and run a Cargo project. It also assumes you have clap = { version = "4", features = ["derive"] } in Cargo.toml and have seen a #[derive(Parser)] struct before.
What makes an argument positional
A positional argument is a value identified by where it appears on the command line, not by a name. In cp a.txt b.txt, the first value is the source and the second is the destination. Neither has a flag in front of it.
In clap's derive API, a field with no #[arg(short)] or #[arg(long)] becomes positional. The order of the fields in the struct is the order of the positions on the command line.
use clap::Parser;
use std::path::PathBuf;
/// Search files for a pattern.
#[derive(Parser, Debug)]
#[command(version, about)]
struct Cli {
/// Text to look for
pattern: String,
/// Files to search
#[arg(value_name = "FILE")]
files: Vec<PathBuf>,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Suppose the package is named grepish. Running grepish error app.log db.log prints:
Cli { pattern: "error", files: ["app.log", "db.log"] }pattern is the first positional, so it takes error. files is the second, so it takes everything left over.
With cargo run, put -- before your own arguments so Cargo does not try to read them: cargo run -- error app.log db.log.
The field type sets the rules
You do not mark positionals as required or optional with a keyword. The Rust type decides.
| Field type | Meaning | Values accepted |
|---|---|---|
| `T` (for example `String`, `PathBuf`, `u32`) | Required | Exactly one |
| `Option<T>` | Optional | Zero or one |
| `Vec<T>` | Optional, repeatable | Zero or more |
| `T` with `default_value` | Optional, never missing in code | Zero or one, falls back to the default |
This is the main benefit of the derive API. If pattern is a String and not an Option<String>, your code never has to handle a missing pattern. Clap reports the problem before main continues.
A missing required value
If you run grepish with no arguments, clap stops and prints an error to stderr:
error: the following required arguments were not provided:
<PATTERN>
Usage: grepish <PATTERN> [FILE]...
For more information, try '--help'.The process exits with code 2. The exact wording can differ slightly between clap 4 releases. The usage line is built from your field types: <PATTERN> is required, and [FILE]... is optional and repeatable.
Placeholder names
In the help output, clap names each positional after its field in upper case. pattern becomes <PATTERN>. To change the text without renaming the field, use value_name:
#[arg(value_name = "FILE")]
files: Vec<PathBuf>,value_name only changes what the user sees in help and usage lines. It has no effect on parsing. The doc comment above each field is the help text for that argument.
Optional values and defaults
A copy tool needs one required source and one destination that is allowed to be missing. There are two ways to model the destination, and they behave differently.
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
struct Cli {
/// File to copy
source: PathBuf,
/// Directory to copy into
#[arg(default_value = ".")]
dest: PathBuf,
}
fn main() {
let cli = Cli::parse();
println!("copy {} into {}", cli.source.display(), cli.dest.display());
}Running copy notes.txt prints copy notes.txt into .. Because dest is a PathBuf and not an Option<PathBuf>, you never need to unwrap it.
Compare the alternatives:
- Use
Option<PathBuf>when "not given" has its own meaning in your program. For example, "write to standard output" is not a path you can name. - Use
default_valuewhen there is a sensible fixed fallback and you want the help output to show it. The help text gains[default: .].
For a non-string default you can use default_value_t = 10, which takes a Rust expression and requires the type to implement Display.
Ordering rules that clap enforces
Clap checks the shape of your positionals against a few rules. Breaking them is a mistake in your definition, not in the user's input. In debug builds clap panics on the first parse, so you find out as soon as you run the program.
- A required positional cannot come after an optional one. With
first: Option<String>followed bysecond: String, a user who gives one value would be ambiguous. Does the value fillfirstorsecond? Clap refuses the definition. - A multi-value positional (
Vec<T>) should be the last positional. TwoVecfields would leave no way to tell where one ends and the next begins. - Positions follow declaration order. Reordering the struct fields changes the command-line interface, and anyone with scripts that call your tool will notice.
Requiring at least one value
A Vec<T> positional accepts zero values by default. If your tool makes no sense without at least one, say so:
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
struct Cli {
/// Files to remove
#[arg(required = true, value_name = "FILE")]
files: Vec<PathBuf>,
}
fn main() {
let cli = Cli::parse();
for f in &cli.files {
println!("would remove {}", f.display());
}
}Now rmfiles with no arguments fails with a "required arguments were not provided" error, and the usage line changes from [FILE]... to <FILE>.... The angle brackets signal that at least one value is required.
Values that start with a dash
Clap reads anything beginning with - as an option or flag. If a positional value legitimately starts with a dash, such as a file named -v, put -- before it. Everything after a bare -- is treated as positional, whatever it looks like:
grepish -- -v app.logHere -v is the pattern, not a flag. This is the standard Unix convention, and users of other tools already expect it.
Negative numbers are a related case. For a positional of type i32, a value like -5 is rejected by default because it looks like a flag. If your tool takes signed numbers as positionals, add allow_negative_numbers = true on that argument. Use allow_hyphen_values = true only when you really want any dash-prefixed text accepted, since it also swallows typos like --vebrose.
Mixing positionals with options
Options and flags can appear before, between, or after positionals. These all produce the same parse for a tool with a positional pattern and a flag --ignore-case:
grepish --ignore-case error app.log
grepish error --ignore-case app.log
grepish error app.log --ignore-caseClap sorts the named arguments out first and assigns the remaining values to positionals in order. The exception is an option that takes a value. In --filter x error, x belongs to --filter, so error is the first positional.
Common errors
- A value is "unexpected". You gave more values than there are positional slots, and no
Vec<T>field collects them. The error readsunexpected argument 'x' found. - A value lands in the wrong field. An
Option<T>positional before aVec<T>takes the first value even when you meant it for the list. Make the order explicit in your docs, or turn the optional value into a--flag. - A type error for a number. A
u32positional givenabcproducesinvalid value 'abc' for '<COUNT>': invalid digit found in string. This is clap's error and exits with code 2 without any code from you. - A panic about positional order at startup. A required positional follows an optional one. Reorder the fields or make the earlier one required.
When to prefer a flag instead
Positionals read well when there is one obvious primary input, such as a file, a pattern, or a URL. Past two or three they become hard to remember, because the user has to know the order. If a value is optional and its meaning is not obvious from its position, make it --dest <DIR> instead. The name documents itself and the order stops mattering.
Exercise
A tool is defined with fields name: String, count: Option<u32>, and tags: Vec<String>, all positional and in that order. A user runs tool report 3 a b. What does each field hold? What happens if the user runs tool report a b?
Show answer
For tool report 3 a b, name is "report", count is Some(3), and tags is ["a", "b"]. For tool report a b, clap assigns "a" to count, which is a u32, so parsing fails with an invalid value 'a' error and exit code 2. The user cannot skip count and still fill tags. A better design makes count a --count option so the tags can follow name directly.