As in Programming a Guessing Game in Rust, it is necessary that we declare the variable inside the loop as:
loop {
let mut guess = String::new();
...
}
But if this mutable variable is declared outside the loop it panics:
let mut guess = String::new();
loop {
...
}
The panic message printed is just:
invalid digit found in string
Why does this happen when the variable guess
has been declared mut
already?
Here's the failing complete code:
use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
let mut guess = String::new();
loop {
println!("Please input your guess.");
io::stdin()
.read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(e) => {
println!("{}", e);
continue;
}
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}