I'm new to rust, what's with this loop?

use std::io::{self, Write};
use std::cmp::Ordering;
use rand::Rng;

fn main() {

let secret_number = rand::thread_rng().gen_range(1, 101);
println!("The secret number is: {}", secret_number);
println!("Guess the number!");

loop {
let mut guess = String::new();

print!("Please input your guess: ");
io::stdout().flush().expect("Failed to flush stdout"); // Use expect() to handle errors   
io::stdin().read_line(&mut guess).expect("Failed to read line");

let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => 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;}
}

}
}

So, the above is my code and my question is in this comment:

when I create a loop - I have to declare the 'guess' string variable within the start of the loop, if I put it outside the loop the program does not function as I want. Why do I have to declare the 'guess' variable within the loop - rather than at the very start of the program like some C++ style programs?

read_line appends to the buffer it takes as argument instead of overriding the buffer's contents. If you define guess outside of the loop, it will fill up with all the lines your user provides as input, including the newline characters at the end. So if I type 42 during the first iteration, guess will be "42\n". Then I type 43 during the second iteration and guess becomes 42\n43\n. This will make parsing guess as u32 fail. This doesn't happen when I create a new buffer during each iteration.

3 Likes

read_line appends to the buffer it takes as argument instead of overriding the buffer's contents.
[/quote]

I was recommended to use:

guess.clear();

at the start of the loop, how interesting

1 Like

The distinction between creating the buffer inside the loop and using clear() is the latter can reuse the same allocated memory buffer. It's slightly faster, but you also can't hand out the created String without cloning it.

1 Like