expression
Clap bounded numeric options
Constrain numeric input at the CLI boundary. A typed parser with a range rejects values outside the supported interval, preventing invalid worker counts from entering application logic. Uses a fixed synthetic argument list or local data. Expected stdout (not executed): workers: 4 Common mistake: Relying only on the numeric type to enforce application-specific bounds.
Formal Syntax & Structure
rust syntaxrust
#[arg(long, value_parser = clap::value_parser!(u16).range(1..=16))]Working Example
Example Snippetrust
fn main() { use clap::Parser; #[derive(Parser)] struct Cli { #[arg(long, value_parser = clap::value_parser!(u16).range(1..=16))] workers: u16, } assert!(Cli::try_parse_from(["report", "--workers", "17"]).is_err()); let cli = Cli::try_parse_from(["report", "--workers", "4"]).unwrap(); println!("workers: {}", cli.workers);}