I have the following match condition that tests whether the entered guess is a valid number (it's from the rust guessing game exercise) :
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
How do I extend the match to check if the number is negative or 0 (I want to throw an error in this case) and proceed normally if the number is positive ?
I tried adding an if on the num inside the Ok case, but that throws an error (probably because num is bound to the value of guess) and also doesn't seem idiomatic.
A match arm can be guarded:
let guess: u32 = match guess.trim().parse() {
Ok(num) if num > 0 => num,
Ok(num) => return Err(whatever),
Err(_) => continue,
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With