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'