Why does using a mutable and an immutable reference in the same expression involving the += operator seem to be sometimes allowed, sometimes not?

Viewed 188

In the below code example, I'm trying to increment the member variable a of the struct X via a mutable reference to it, in four different ways. Here, the compiler gives the following error for the line denoted by B:

error[E0502]: cannot borrow `*x` as immutable because it is also borrowed as mutable
  --> src\main.rs:17:23
   |
17 |     *x.get_a_mut() += x.get_a(); //B DOESN'T COMPILE
   |     ------------------^--------
   |     ||                |
   |     ||                immutable borrow occurs here
   |     |mutable borrow occurs here
   |     mutable borrow later used here

If it is a problem to use a mutable and an immutable reference to a in the same expression, why does C and D compile?

struct X {
    a: i64,
}

impl X {
    pub fn get_a_mut(&mut self) -> &mut i64 {
        return &mut self.a;
    }

    pub fn get_a(&self) -> &i64 {
        return &self.a;
    }
}

fn my_fn(x: &mut X) {
    *x.get_a_mut() += 5; //A
    *x.get_a_mut() += x.get_a(); //B DOESN'T COMPILE
    *x.get_a_mut() += 2 * x.get_a(); //C
    *x.get_a_mut() = x.get_a() + x.get_a(); //D
}

fn main() {
    let mut x = X { a: 50 };
    my_fn(&mut x);
}
1 Answers

According to += documentation, you are calling something like add_assign(lhs: &mut i64, rhs: &i64) in case B and something like add_assign(lhs: &mut i64, rhs: i64) in cases A, C and D.

In case A, rhs is a constant, different from x.a; no problem.

In case C, rhs is a temporary (the result of 2 * x.get_a()) and does not need to keep a reference on x.a to exist; no problem.

In case D, rhs is a temporary (the result of x.get_a() + x.get_a()) and does not need to keep a reference on x.a to exist; no problem.

But when it comes to case B, rhs is a reference on x.a; then this call uses both a mutable (lhs) and immutable (rhs) reference on the same data (x.a) at the same time, which is forbidden.

You could eventually clone rhs: *x.get_a_mut() += x.get_a().clone().

Related