2

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;
            }
        }
    }
}
Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
Aditya Nigam
  • 869
  • 2
  • 11
  • 21
  • 2
    Please post the error message. We have no idea where it errors. Also include the relevant code inside the `loop` block – sshashank124 Jan 14 '20 at 10:23
  • @sshashank124 check again, updated – Aditya Nigam Jan 14 '20 at 10:32
  • @AdityaNigam "Also include the relevant code". SO questions are supposed to be self-contained. Yours should include an [MRE]. – mcarton Jan 14 '20 at 10:37
  • @mcarton added the failing code, and here when the `guess` declaration is moved inside the loop, there's no errors – Aditya Nigam Jan 14 '20 at 10:42
  • 4
    When it is out of loop, you are reading more than one line into a `String`, then you are trying to parse the `String` as number, at the end it can't parse multiple lined string into a number – Ömer Erden Jan 14 '20 at 10:50
  • 4
    Quoting [the doc](https://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_line): *Read all bytes until a newline (the 0xA byte) is reached, and append them to the provided buffer.* which means you append the line every time in your loop which will of course fail to parse the number at some time. – hellow Jan 14 '20 at 10:51
  • 2
    @hellow Thanks, could you move your comment to answers so I can mark the question as answered? – Aditya Nigam Jan 14 '20 at 10:58
  • 1
    @AdityaNigam no, because the provided duplicate answer exactly matches your question. (+ I can't answer questions marked as duplicate) – hellow Jan 15 '20 at 08:56

0 Answers0