Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust match on number condition

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.

like image 397
KDN Avatar asked Oct 25 '25 01:10

KDN


1 Answers

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,
};
like image 122
mcarton Avatar answered Oct 28 '25 04:10

mcarton