I'm reading chapter two of The Rust Programming Language and something I don't understand caught my eye in here:
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
println!("You guessed: {}", guess);
}
On code line 5, it declares a mutable variable with let mut guess = String::new()
, but on the next line the argument for read_line()
also has a mut
keyword.
If the variable was defined as mutable in the first place, then why do we use mut
again instead of just using the reference like this:
io::stdin().read_line(&guess).expect("Failed to read line");
If the type is defined for the variable, then when we use reference, shouldn't the type (mut
) exist by default?