为什么我不能在可变引用上使用`+ =`?

时间:2017-03-08 16:12:35

标签: compiler-errors rust

我想将+=应用于可变引用(&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'

0 个答案:

没有答案