I'm trying to improve on the final guessing game sample code a bit. Particularly, I plan to output "Please input a number!" if the user does not input a number rather than "Please input your guess." again. I'm doing this with an inner loop. The code below does work:
let guess: u32;
loop {
let mut guess_str = String::new();
io::stdin().read_line(&mut guess_str)
.ok()
.expect("Failed to read line");
guess = match guess_str.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Please input a number!");
continue;
}
};
break;
}
I'd like to avoid the guess_str
if I can by properly shadowing the matches. If I change guess_str
to guess
, Rust complains of use of possibly uninitialized variable: `guess`
. I'm not sure how the variable could possibly be uninitialized if it's impossible for it to not be uninitialized with the code above. Is there any way to do this only using guess
?