Hi all,
I again have a borrowing question, in know a way around, but I think that just shows I have not understood what is going on.... I isolated my code to this example:
use std::sync::{Mutex};
#[derive(Debug)]
struct MyStruct {
a: [i32; 5],
i: usize
}
impl MyStruct {
fn new() -> MyStruct {
MyStruct {a: [0;5], i: 3}
}
}
fn main() {
let mut myvar = MyStruct::new();
println!("{:?}", myvar);
let my_mutex = Mutex::new(myvar);
let mut my_new_var = my_mutex.lock().unwrap();
my_new_var.a[my_new_var.i] = 1; //error[E0502]: cannot borrow `my_new_var` as immutable because it is also borrowed as mutable
println!("{:?}", my_new_var);
}
I think I understand vaguely why it is giving an error (the index in must not be a mutable var, though interesting enough without the Mutex it works).
My current workaround is to assign my_new_var.i to a local unmutable variable and use it instead. But I am sure there is a better way doing this. Can you enlighten me?
(using something like that in an application state variable while using Actix)
This is because of the Deref trait. my_new_var has the type MutexGuard<'_, MyStruct>, which implements both Deref and DerefMut. The Deref trait cannot provide access to disjoint fields on it's own, so you must acquire an exclusive reference explicitly before you can use disjoint fields.
fn main() {
let mut myvar = MyStruct::new();
println!("{:?}", myvar);
let my_mutex = Mutex::new(myvar);
let mut my_new_var = my_mutex.lock().unwrap();
let my_new_var = &mut *my_new_var;
my_new_var.a[my_new_var.i] = 1; //works
println!("{:?}", my_new_var);
}