Tutorial help with references


On this page, this line of code I don't understand io::stdin().read_line(&mut guess).expect("Failed to read line");

Why can't this function read_line(&mut guess) also accept this argument read_line(guess)?

Quoting the book:

For now, all you need to know is that like variables, references are immutable by default. Hence, you need to write &mut guess rather than &guess to make it mutable. (Chapter 4 will explain references more thoroughly.)

guess must be written, and to do that the function needs a mutable reference to a String.
When you will reach chapter 4, things are explained better.

1 Like

What your highlighting is an output parameter. Functions can’t be overloaded so such a change would need to be using another name. If you were to move the string into the function you then would need the return type to also take the value back, as well as report if there is an error.

1 Like

If you mean why it can't semantically — that's because read_line(guess) gives ownership of guess to read_line() (it means "take it and keep it"), and after ownership is passed to code in the function, the code outside of the function can't use the value any more (a value is always in one place, with one owner).

If you mean syntactically why borrowing is so noisy in Rust, it's because Rust wants to be explicit about it. References place restrictions on referenced data, so it's useful to see where these restrictions come from.