How does assigning to a borrowed variable violate the rules of references?

2k views Asked by At

I have this code:

struct Foo<'a> {
    link: &'a i32,
}

fn main() {
    let mut x = 33;
    println!("x:{}", x);
    let ff = Foo { link: &x };
    x = 22;
}

Which generates this compiler error:

error[E0506]: cannot assign to `x` because it is borrowed
 --> src/main.rs:9:5
  |
8 |     let ff = Foo { link: &x };
  |                           - borrow of `x` occurs here
9 |     x = 22;
  |     ^^^^^^ assignment to borrowed `x` occurs here

The Rust book has only two rules:

  1. one or more references (&T) to a resource,
  2. exactly one mutable reference (&mut T).

I have one mutable variable and one immutable link. Why does the compiler give an error?

1

There are 1 answers

3
Shepmaster On

The Rust Programming Language defines the rules of references:

  • At any given time, you can have either one mutable reference or any number of immutable references.
  • References must always be valid.

Reassigning a variable implicitly requires a mutable reference:

fn main() {
    let mut x = 33;
    let link = &x;
    x = 22;
    *(&mut x) = 22; // Basically the same thing
}

Importantly, reassigning a variable mutates the variable, which would cause the value of the immutable reference link to change, which is disallowed.

Note that the initial assignment of the variable does not require the variable to be mutable:

fn main() {
    let x;
    // Some other code
    x = 42;
}