-1

From my understanding, the mut in let mut means a mutable variable binding, while the mut in &mut means an exclusive borrow. However, the following code:

fn main() {
    let x = 1;
    let x_ref = &mut x;
}

won't compile. It looks like that the mut in let mut does not only mean a mutable variable binding, but also implies curtain mutable borrow constraints. What's the precise semantics of mut in let mut?

yeshengm
  • 557
  • 5
  • 13
  • Because X is not mutable so it will not change now and in the future, see [this](https://doc.rust-lang.org/1.8.0/book/references-and-borrowing.html). However, you are trying to obtain a *mutable* reference of X and this is not possible due to the fact that X is *NOT mutable*, nevertheless you can still obtain the "reference" of X into X_REF without the *mut* keywork since X_REF and &X are not mutable(s). – Carlo Corradini Jul 08 '20 at 09:03
  • 1
    Does this answer your question? [What's the difference between placing "mut" before a variable name and after the ":"?](https://stackoverflow.com/questions/28587698/whats-the-difference-between-placing-mut-before-a-variable-name-and-after-the) – E_net4 Jul 08 '20 at 09:07
  • In order to mutably borrow `x`, the binding to that variable also needs to be declared as `mut`: `let mut x = 1;` More details in the linked question. See also: https://stackoverflow.com/questions/47760006 – E_net4 Jul 08 '20 at 09:09

1 Answers1

2

It looks like that the mut in let mut does not only mean a mutable variable binding, but also implies curtain mutable borrow constraints.

Ignoring interior mutability, you can only take a mutable borrow from a mutable binding because... they're functionally the same thing:

let mut x = 1;
let x_ref = &mut x;
*x_ref = 2;
println!("{}", x); // prints 2

What's the precise semantics of mut in let mut?

It declares a mutable binding, which means both that the binding can be updated in-place (assigned to) and can be mutably referenced.

Masklinn
  • 34,759
  • 3
  • 38
  • 57