我想将+=
应用于可变引用(&mut
),但我不明白为什么它不能编译:
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 !
}
我认为&mut Num += Num
有效,因为add_assign
需要&mut self
。
但编译错误是:
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'