Sub topic 7
Parsing values into Rust types
This chapter assumes you can define a #[derive(Parser)] struct with positional arguments and options, and that you are comfortable with FromStr, Result, and Option. Here you will see how clap turns the raw text of each argument into a typed field, how to tighten that conversion, and how to supply your own.
Every value starts as text
The operating system hands your program a list of strings. Clap's job is to convert each one into the type you declared for the field. The converter is called a value parser. It takes one string and returns either a typed value or an error message.
When the conversion fails, clap prints the error, mentions the argument that caused it, and exits with code 2. Your main never sees a half-valid struct.
Types that work without configuration
If you write nothing, clap picks a value parser from the field's type. The derive macro also looks through Option<T> and Vec<T> and applies the parser to T.
| Field type | What clap does |
|---|---|
| `String` | Accepts any valid UTF-8 text |
| `PathBuf`, `OsString` | Accepts any text, including bytes that are not valid UTF-8 |
| `u8`, `u32`, `i64`, and other integers | Parses the number and rejects values outside the type's range |
| `f64`, `char`, and other `FromStr` types | Calls `FromStr::from_str` |
| `bool` | Treated as a flag with no value, not parsed from text |
| `Option<T>` | Argument is optional, `None` when absent |
| `Vec<T>` | Argument may be repeated, one `T` per occurrence |
The practical consequence is that a String field rejects a non-UTF-8 file name, while a PathBuf field accepts it. Use PathBuf for anything that names a file.
use clap::Parser;
use std::path::PathBuf;
#[derive(Parser, Debug)]
struct Cli {
/// File to read
input: PathBuf,
/// How many times to retry
#[arg(long, default_value_t = 3)]
retries: u32,
/// Scale factor
#[arg(long)]
ratio: Option<f64>,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}Running this with --retries abc produces:
error: invalid value 'abc' for '--retries <RETRIES>': invalid digit found in string
For more information, try '--help'.The second line of the message names the option and the offending text. The last part, invalid digit found in string, is the error message from the standard library's integer parser, passed through unchanged.
Narrowing a type with a range
An integer type often allows more values than your program does. A u8 accepts 0 to 255, but a worker count may only make sense from 1 to 16. The value_parser! macro builds the default parser for a type, and integer parsers have a range method.
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Number of worker threads (1 to 16)
#[arg(
long,
default_value_t = 4,
value_parser = clap::value_parser!(u8).range(1..=16)
)]
workers: u8,
}
fn main() {
let cli = Cli::parse();
println!("using {} workers", cli.workers);
}With --workers 99, clap reports 99 is not in 1..=16. With --workers 0, it reports 0 is not in 1..=16. Without the range, both values would be accepted, because both fit in a u8.
Writing your own parser function
For anything that is not a plain number, pass a function to value_parser. The function takes &str and returns Result<T, E>. The error type E can be a String or any standard error type. Clap shows the error's message to the user.
This example parses durations such as 250ms, 30s, or 5m:
use clap::Parser;
use std::time::Duration;
fn parse_duration(s: &str) -> Result<Duration, String> {
let split = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
let (digits, unit) = s.split_at(split);
let n: u64 = digits
.parse()
.map_err(|_| format!("`{s}` must start with a whole number"))?;
match unit {
"ms" => Ok(Duration::from_millis(n)),
"s" | "" => Ok(Duration::from_secs(n)),
"m" => Ok(Duration::from_secs(n * 60)),
_ => Err(format!("unknown unit `{unit}`, use ms, s, or m")),
}
}
#[derive(Parser, Debug)]
struct Cli {
/// How long to wait, such as 250ms, 30s, or 5m
#[arg(long, value_parser = parse_duration, default_value = "30s")]
timeout: Duration,
}
fn main() {
let cli = Cli::parse();
println!("timeout = {:?}", cli.timeout);
}Two details matter here:
- The field type is
Duration, notString. The field type must match what the parser function returns. default_value = "30s"is a string, and clap runs it through the same parser. A default that your own parser rejects fails when the program starts parsing, so you notice it immediately.
Contrast this with default_value_t = 3 from the first example. That form takes a Rust value and requires the field type to implement Display. Use default_value_t when the field type is simple, and default_value when you want the parser to run on a string.
If your type already implements FromStr, you do not need a function. Clap uses FromStr automatically, and the error type's Display output becomes the message.
Several values for one argument
A Vec<T> field collects values. By default the user repeats the option:
use clap::Parser;
#[derive(Parser, Debug)]
struct Cli {
/// Tag to apply, may be given more than once
#[arg(long = "tag")]
tags: Vec<String>,
/// Comma-separated list of ids
#[arg(long, value_delimiter = ',')]
ids: Vec<u32>,
}
fn main() {
let cli = Cli::parse();
println!("{cli:?}");
}--tag a --tag b gives ["a", "b"]. --ids 1,2,3 gives [1, 2, 3], and each piece is parsed as a u32 separately. If one piece is bad, as in --ids 1,x,3, the whole argument is rejected. An absent Vec is an empty vector, not an error.
Gotchas
- Negative numbers. A token that starts with
-looks like an option.--offset -5fails with an unexpected argument error. Write--offset=-5, or addallow_negative_numbers = trueto the argument. - Parser and field type disagree. If
value_parserproduces aDurationbut the field isu64, parsing may compile and then panic at runtime. RunCli::command().debug_assert()in a test (covered in a later chapter) to catch this. - Validation inside the parser. Keep checks that depend on one value in the parser. Checks that compare two arguments belong in constraints or in your program logic.
- Error text is user-facing. Write parser messages for the person at the terminal. Say what was wrong and what is accepted, as
parse_durationdoes.
Exercises
Exercise
A field is declared #[arg(long)] limit: Option<u16>. What happens for --limit 70000, and what is the value of limit when the user passes no --limit at all?
Show answer
Clap rejects 70000 because it is outside the range of u16 (0 to 65535), prints an invalid value error, and exits with code 2. When --limit is absent, limit is None.
Exercise
Write a parser function parse_percent(s: &str) -> Result<u8, String> that accepts 0 to 100, with or without a trailing % (for example 75 and 75%). Then show the field declaration that uses it.
Show answer
fn parsepercent(s: &str) -> Result<u8, String> {
let trimmed = s.stripsuffix('%').unwrapor(s);
let n: u8 = trimmed.parse().maperr(|| format!("{s} is not a whole number"))?;
if n <= 100 { Ok(n) } else { Err(format!("{s} is above 100")) }
}
The field is `#[arg(long, valueparser = parse_percent)] cpu: u8,. The field type u8` matches the function's return type.