为什么允许一个数字类型的向量在一个表达式中具有不变且可变的借位?

Here is an examle of a: Vec<usize> can be mutably borrowed and immutably referenced in one expression:

fn main() {
    let mut a = vec![0, 1];
    a[0] += a[1]; // OK
}

I thought it can be compiled because usize implements Copy trait, and I created a struct that implements Copy trait, and compile it like the above example, but it failed:

use std::ops::AddAssign;

#[derive(Clone, Copy, PartialEq, Debug, Default)]
struct MyNum(usize);

impl AddAssign for MyNum {
    fn add_assign(&mut self, rhs: MyNum) {
        *self = MyNum(self.0 + rhs.0)
    }
}

fn main() {
    let mut b = vec![MyNum(0), MyNum(1)];
    b[0] += b[1]; // cannot borrow `b` as immutable because it is also borrowed as mutable
}

playground

  1. Why my MyNum didn't behave in the same way as usize, though it implements Copy trait?
  2. Why vector of usize can be mutably borrowed and immutably referenced in one expression?
评论