a is a Vec<i32> which can be mutably and immutably referenced in one expression:
fn main() {
let mut a = vec![0, 1];
a[0] += a[1]; // OK
}
I thought this compiled because i32 implements Copy, so I created another type that implements Copy and compiled it like the first example, but it fails:
use std::ops::AddAssign;
#[derive(Clone, Copy, PartialEq, Debug, Default)]
struct MyNum(i32);
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];
}
error[E0502]: cannot borrow `b` as immutable because it is also borrowed as mutable
--> src/main.rs:14:13
|
14 | b[0] += b[1];
| --------^---
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
| mutable borrow later used here
- Why does my
MyNumnot behave in the same way asi32even though it implementsCopy? - Why can the vector be mutably and immutably referenced in one expression?