rust - Borrowing reference and guard together from a Mutex -
i'm trying encapsulate code avoid repeating it, relating borrowing data out of mutex , further operations thereupon (which leave off of question out of scope, motivating factors).
the following sample code complains guard
not live long enough. precisely why i'm returning guard
in structure designed expressly purpose.
is limitation of borrow checker? suggestions on working around this?
use std::sync::{mutex,mutexguard}; use std::ops::derefmut; pub struct innerdata { count: i32 // sample } pub struct data { pub inner_data: mutex<innerdata> } pub struct borrowedinnerdata<'a> { pub inner_data: &'a mut innerdata, guard: mutexguard<'a,innerdata>, } impl data { pub fn borrow_inner_data<'a>(&'a mut self) -> borrowedinnerdata<'a> { let guard = self.inner_data.lock().unwrap(); borrowedinnerdata { inner_data: guard.deref_mut(), guard: guard, } } } fn main() { let mut data = data { inner_data: mutex::new( innerdata { count: 5 }), }; let borrowed_inner_data = data.borrow_inner_data(); }
let's @ derefmut
trait:
pub trait derefmut: deref { fn deref_mut(&'a mut self) -> &'a mut self::target; }
this means when deref_mut
called, reference returned lives long value being dereferenced. however, moving guard
when move borrowedinnerdata
. means value stops living @ 1 memory location , starts @ new one. veedrac hints at, it's entirely possible moving guard, invalidate reference. bad , lead crashes (in best case).
however, there's no real reason keep guard
, inner_data
. because of deref
, derefmut
, mutexguard<innerdata>
can used &innerdata
or &mut innerdata
. remove inner_data
struct , keep guard
.
Comments
Post a Comment