I'm having trouble getting my code to compile: MutexGuard
is enforcing borrow checking rules that seem to be unnecessary to me. In particular, declaring the same struct
without wrapping it in the Mutex
would allow both mutable references to the disjoint fields of the struct.
use std::sync::Mutex;
struct S {
a: usize,
b: usize,
}
fn main() {
let s = Mutex::new(S { a: 0, b: 1 });
let mut s = s.lock().ok().expect("mutex error");
let a = &mut s.a;
let b = &mut s.b;
*a = 1;
*b = 2;
}
Compiler error:
error[E0499]: cannot borrow `s` as mutable more than once at a time
--> src/main.rs:15:18
|
14 | let a = &mut s.a;
| - first mutable borrow occurs here
15 | let b = &mut s.b;
| ^ second mutable borrow occurs here
16 |
17 | *a = 1;
| ------ first borrow later used here
What can I do to bypass the above issue?
Playground: Rust Playground