Why is it required to explicitly cast an argument as 'mut' when passing it to read_line()?


#1

Hi,

I am new to Rust, but have been programming C for a while now.
I started with the “Guessing game” project in the Rust tutorial. The read_line() invocation involves passing a variable already declared as ‘mut’ recast (if I may use that terminology) as ‘mut’. Why is this necessary? Does the use of ‘let’ not stamp a “permanent” association of the mutable property on the variable?

Thanks,
Pavan


#2

Here are the relevant lines from the tutorial:

let mut guess = String::new();
io::stdin().read_line(&mut guess)

guess is a variable of type String. But read_line takes an argument of type &mut String (mutable borrowed pointer to String). These types are different, so we can’t pass guess directly to read_line.

To get a value of type &mut String we can borrow a pointer to guess. There are two types of borrowed pointer in Rust, each with their own syntax for borrowing:

let p1: &String = &guess;
let p2: &mut String = &mut guess;

Since read_line needs a mutable pointer, we need to use the second syntax. For more details, see the References and Borrowing chapter of the Rust Programming Language book.


#3

To put things simpler, &mut X is not “recasting”, it is “borrowing”. This way you give the function not the variable itself, but a reference to the variable (&) which allows function to write to the original variable (mut), that is &mut to put two pieces together.


#4

First, thanks for responding in detail to this naive query and thanks for pointing me to the “References and Borrowing” chapter. Reading it resolved some of my doubts. However, the key misunderstanding I had was about the ‘mut’ keyword. I had initially assumed that declaring something as ‘mut’ makes the variable and its references mutable. That does not seem to be the case. A reference has to be explicitly declared mutable when mutability is desired. Thanks again.


#5

Thanks. I had misunderstood the effect of ‘mut’. Please see response to @mbrubeck.