0
fn main() {
    let mut input = String::new();

    loop {
        std::io::stdin()
            .read_line(&mut input)
            .expect("error: unable to read user input");

        println!("input is: {}", input);
    }
}

When I first enter hello it will show input is: hello, then no matter what I enter later it will always show input is: hello, so read_line doesn't mutate the input variable. Why does this happen?

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98
jr6tp
  • 485
  • 1
  • 5
  • 15

1 Answers1

3

read_line does mutate the input variable, but it does so by appending to it, not overwriting it. If you'd like to overwrite input you should first clear it before passing it to read_line which will give you the behavior you're looking for:

fn main() {
    let mut input = String::new();

    loop {
        input.clear(); // truncate string contents
        std::io::stdin()
            .read_line(&mut input)
            .expect("error: unable to read user input");

        println!("input is: {}", input);
    }
}
pretzelhammer
  • 13,874
  • 15
  • 47
  • 98