Mutable Variable in the Guessing Game

Hello! I'm learning Rust and was going through the guessing game program in the Rust Programming book (pages 25 - 42). I was wondering if anyone could tell me why I can't move the line

let mut guess = String::new();

outside of the loop? When I do, only the first guess is read in. After that, the loop just continues without actually processing any input. I would have expected that since it's mutable I can just keep reading into it each loop iteration, but this doesn't appear to be the case...

BufRead::read_line appends to the buffer. When you recreate 'guess' for every iteration of the loop, the buffer is empty and the line is the only thing in the buffer. If you create it outside the loop, the buffer will have all the lines and parse() will parse the first number it finds (the first line) over and over.

A little correction: parse() returns an Err.

This is correct. You'd have to write .clear() as well to move it outside.

So are you saying that the guess variable is acting as the buffer? And read_line more or less "concatenates" to the end of it? If so, why does .parse() return an error?


Yup. See its docs: Stdin in std::io - Rust and BufRead in std::io - Rust

Once found, all bytes up to, and including, the delimiter (if found) will be appended to buf.

parse() can return an error if what is read is not a number:

See here: Rust Playground

Ok, I understand now. Thank you!