Mutable Variable in the Guessing Game


#1

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…


#2

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.


#3

A little correction: parse() returns an Err.


#4

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


#5

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?


#6

Yup!

Yup. See its docs: http://doc.rust-lang.org/std/io/struct.Stdin.html#method.read_line and http://doc.rust-lang.org/std/io/trait.BufRead.html#method.read_line

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: http://is.gd/ftdt3X


#7

Ok, I understand now. Thank you!