expression
Typed option values: parse and validate
Parsing transforms input text into a type; semantic validation then checks the allowed domain. A worker count of zero is representable as u16 but invalid for this application. Keeping validation separate makes failure modes easier to explain. Uses a fixed synthetic argument list or local data. Expected stdout (not executed): workers: 4 Common mistake: Assuming every successfully parsed number is valid for the application.
Formal Syntax & Structure
rust syntaxrust
raw.parse::<u16>()Working Example
Example Snippetrust
fn main() { fn workers(raw: &str) -> Result<u16, &'static str> { let n = raw.parse::<u16>().map_err(|_| "expected a number")?; if !(1..=16).contains(&n) { return Err("expected 1 through 16"); } Ok(n) } assert_eq!(workers("0"), Err("expected 1 through 16")); assert!(workers("abc").is_err()); println!("workers: {}", workers("4").unwrap());}