Validating arguments in Rust
clap can enforce ranges, enumerations and required combinations before main runs.
use clap::{Parser, ValueEnum};
#[derive(Copy, Clone, Debug, ValueEnum)]
enum Theme {
Default,
Monokai,
Dracula,
}
#[derive(Parser, Debug)]
struct Cli {
#[arg(long, value_parser = 1..=3)]
stars: i64,
#[arg(long, value_enum, default_value_t = Theme::Default)]
theme: Theme,
#[arg(long, requires = "output")]
export: bool,
#[arg(long)]
output: Option<String>,
}
fn main() {
let cli = Cli::parse();
println!("{:?}", cli);
}
How it works
value_parserwith a range rejects out-of-bounds numbers.- A
ValueEnumrestricts a flag to known values. requiresandconflicts_withexpress the pairings.
Keywords and builtins used here
CliDefaultOptionStringThemeboolenumfni64letmainstructuse
The run, in numbers
- Lines
- 28
- Characters to type
- 425
- Tokens
- 89
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 53 seconds.
Step 5 of 5 in Arguments, step 5 of 12 in CLI tools & HTTP clients.