With a simple object, I can get mutable references to individual fields:
struct MyObject {
pub a: i32,
pub b: i32,
}
fn func_1(obj: &mut MyObject) {
let a = &mut obj.a;
let b = &mut obj.b;
*a += 1;
*b *= 2;
}
This doesn't work if obj
is a MutexGuard
or RefMut
:
fn func_3(mtx: &Mutex<MyObject>) {
let mut obj = mtx.lock().unwrap();
let a = &mut obj.a;
let b = &mut obj.b; // fails
...
}
fn func_4(rfc: &mut RefCell<MyObject>) {
let mut obj = rfc.borrow_mut();
let a = &mut obj.a;
let b = &mut obj.b; // fails
...
}
Both fail with:
error[E0499]: cannot borrow `obj` as mutable more than once at a time
--> src/main.rs:28:18
|
27 | let a = &mut obj.a;
| --- first mutable borrow occurs here
28 | let b = &mut obj.b; // fails
| ^^^ second mutable borrow occurs here
However, this does work if obj
is a Box
:
fn func_2(obj: &mut Box<MyObject>) {
let a = &mut obj.a;
let b = &mut obj.b;
*a += 1;
*b *= 2;
}
See it on the Rust Playground.
My main question is why. Why does the compiler know that this is okay for Box
, but not for the others? Is Box
special?