I have the following code for which borrow checking fails.
I know the nested mutex does not make sense, but I'm designing a XXXguard pattern where nested use should be possible, and having trouble getting past the borrow checker.
Access to a & b is orthogonal so I think it should not be a problem (It indeed isn't a problem when I use the comment out code).
I wonder why the borrow checker has to complain about it, and is there a way I can design XXXguard so that I can use recursively?
use std::sync::Mutex;
struct MyStruct {
a: Mutex<i32>,
b: i32,
}
impl MyStruct {
pub fn new() -> Self {
Self {
a: Mutex::new(0),
b: 0,
}
}
}
fn main( ) {
let x = Mutex::new(MyStruct::new());
let mut xg = x.lock().unwrap();
// let mut xg = MyStruct::new(); // This is okay
let mut a = xg.a.lock();
xg.b = 0;
}
Errors:
Compiling playground v0.0.1 (/playground)
warning: unused variable: `a`
--> src/lib.rs:20:13
|
20 | let mut a = xg.a.lock();
| ^ help: if this is intentional, prefix it with an underscore: `_a`
|
= note: `#[warn(unused_variables)]` on by default
warning: variable does not need to be mutable
--> src/lib.rs:20:9
|
20 | let mut a = xg.a.lock();
| ----^
| |
| help: remove this `mut`
|
= note: `#[warn(unused_mut)]` on by default
error[E0502]: cannot borrow `xg` as mutable because it is also borrowed as immutable
--> src/lib.rs:21:5
|
20 | let mut a = xg.a.lock();
| -- immutable borrow occurs here
21 | xg.b = 0;
| ^^ mutable borrow occurs here
22 | }
| - immutable borrow might be used here, when `a` is dropped and runs the destructor for type `Result<MutexGuard<'_, i32>, PoisonError<MutexGuard<'_, i32>>>`
For more information about this error, try `rustc --explain E0502`.
warning: `playground` (lib) generated 2 warnings
error: could not compile `playground` due to previous error; 2 warnings emitted