1

I want to apply += to a mutable reference (&mut), but I do not understand why it does not compile:

use std::ops::AddAssign;

struct Num {
    value: usize,
}

impl AddAssign for Num {
    fn add_assign(&mut self, other: Num) {
        self.value += other.value;
    }
}

fn main() {
    let mut n1 = Num { value: 42 };
    let n2 = Num { value: 41 };
    n1 += n2; // It work!

    let ref mut rn1 = n1; // Get &mut Num
    let n2 = Num { value: 41 };
    rn1 += n2; // It could not be compiled !
}

I think &mut Num += Num is valid because add_assign takes &mut self.

But the compiler error is:

error[E0368]: binary assignment operation `+=` cannot be applied to type `&mut Num`
  --> src/main.rs:20:5
   |
20 |    rn1 += n2;
   |    ^^^ cannot use '+=' on type '&mut Num'
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • Specifically, you need `impl<'a> AddAssign for &'a mut Num {` and then `let mut rn1 = &mut n1;`. – Shepmaster Mar 08 '17 at 16:22
  • Thanks for answer. Is there difference between `let ref mut rn1 = n1;` and `let mut rn1 = &mut n1` ? – Atsuki Takahashi Mar 08 '17 at 16:30
  • Yes. One produces a mutable reference (`rn1: &mut Foo`), the other produces a mutable mutable reference (`mut rn1: &mut Foo`). See http://stackoverflow.com/q/28587698/155423. Said more concisely, one works here, the other doesn't. Also `let mut ref x = foo`, while valid, is not idiomatic; `let x = &mut foo` is. – Shepmaster Mar 08 '17 at 16:33

0 Answers0