Amani
Amani

Reputation: 18123

Why do I need to repeat writing `mut` the second time?

A mutable variable is declared and initialized with the keyword mut, but when it's used in the next line of code, the keyword mut must be repeated;

let mut guess = String::new();

io::stdin()
    .read_line(&mut guess)
    .expect("Failed to read line");

My expectation is that once a variable is declared and initialized as mutable, it remains to be so. Is this a syntactic sugar or is there a specific reason for this?

I would expect the above code to be like this:

let mut guess = String::new();

io::stdin()
    .read_line(&guess)
    .expect("Failed to read line");

Note that I have omitted the mut keyword in the call to read_line.

Upvotes: 1

Views: 161

Answers (1)

Shepmaster
Shepmaster

Reputation: 430466

I strongly encourage you to go back and re-read The Rust Programming Language, second edition, specifically the section on references and borrowing.

There are two types of references: immutable and mutable. Even if a variable may be mutated, you can choose to get an immutable reference to it. You make this choice by saying &foo or &mut foo.

This capability is important to allow you to adhere to the rules of references:

  1. At any given time, you can have either but not both of:
    • One mutable reference.
    • Any number of immutable references.

As BufRead::read_line requires a mutable reference to a String, you need to say &mut guess.

Upvotes: 6

Related Questions