Sub topic 7
Parsing values into Rust types
This chapter assumes you can define a struct with #[derive(Parser)] and add options with #[arg(long)]. Here you will see how clap turns the text on the command line into typed fields, and what happens when that conversion fails.
How clap picks a parser
The operating system gives your program a list of strings. clap picks a value parser for each argument from the field's type. The parser converts the text into that type or returns an error message.
For common types you write nothing extra:
| Field type | Accepts |
|---|---|
| `String`, `PathBuf` | any text |
| `u8`, `u16`, `i32`, `u64`, `f64` | numbers that fit the type |
| `Option<T>` | the value may be absent |
| `Vec<T>` | the option can repeat |
A u8 field rejects 300 because it does not fit. A u32 field rejects -1. clap checks this before main sees the struct.
Range checks and custom parsers
Use value_parser when the type alone is not enough. The built-in integer parsers have a range method. For other types, pass a function that takes &str and returns Result<T, E>.
use clap::Parser;
use std::time::Duration;
fn parse_seconds(s: &str) -> Result<Duration, String> {
let secs: u64 = s
.parse()
.map_err(|_| format!("`{s}` is not a whole number of seconds"))?;
Ok(Duration::from_secs(secs))
}
#[derive(Parser, Debug)]
struct Cli {
/// Port to listen on
#[arg(long, default_value_t = 8080, value_parser = clap::value_parser!(u16).range(1..=65535))]
port: u16,
/// Timeout in seconds
#[arg(long, default_value = "30", value_parser = parse_seconds)]
timeout: Duration,
/// Item id, repeat for several
#[arg(long = "id")]
ids: Vec<u32>,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Running cargo run -- --port 9000 --id 1 --id 2 prints Cli { port: 9000, timeout: 30s, ids: [1, 2] }. Running cargo run -- --port 0 fails before main uses the value:
error: invalid value '0' for '--port <PORT>': 0 is not in 1..=65535The Err string from parse_seconds becomes the text after the colon in that same kind of message.
Common errors
- Using a
Stringfield and parsing it yourself later. The error then appears after clap has finished and does not look like clap's other errors. Put the conversion in a value parser. - Expecting
default_valueto bypass the parser. The default text goes through the parser too.default_value = "30"works withparse_secondsonly because"30"is valid input. Usedefault_value_twhen you already have a typed value. - Returning an error type clap cannot display. The function's error type must convert into a boxed error.
Stringand most standard error types work. - Forgetting that
Vec<T>is optional. With no--idgiven, you get an empty vector, not an error.
Exercise
A field is declared #[arg(long)] retries: u8. What happens when the user passes --retries 300, and where does the check happen?
Show answer
clap's built-in u8 value parser rejects 300 because it does not fit in a u8. It prints an "invalid value" error and exits with code 2 before main receives the struct, so your code never sees an out-of-range value.