I have a structure that looks something like this:
pub struct MyStruct { data: Arc<Mutex<HashMap<i32, Vec<i32>>>>, }
I can easily get a mutex lock and request a basic HashMap :
let d = s.data.lock().unwrap(); let v = d.get(&1).unwrap(); println!("{:?}", v);
Now I want to create a method to encapsulate the request, so I am writing something like this:
impl MyStruct { pub fn get_data_for(&self, i: &i32) -> &Vec<i32> { let d = self.data.lock().unwrap(); d.get(i).unwrap() } }
This obviously does not compile, because I'm trying to return a link to the data under the mutex:
error: `d` does not live long enough --> <anon>:30:9 | 30 | d.get(i).unwrap() | ^ | note: reference must be valid for the anonymous lifetime #1 defined on the block at 28:53... --> <anon>:28:54 | 28 | pub fn get_data_for(&self, i: &i32) -> &Vec<i32> { | ^ note: ...but borrowed value is only valid for the block suffix following statement 0 at 29:42 --> <anon>:29:43 | 29 | let d = self.data.lock().unwrap(); | ^
I can fix this by wrapping the HashMap values ββin Arc , but it looks ugly ( Arc in Arc ) and complicates the code:
pub struct MyStruct { data: Arc<Mutex<HashMap<i32, Arc<Vec<i32>>>>>, }
What is the best way to approach this? Is it possible to make a method that does what I want without changing the data structure?
Full code example .
rust
Sergey Mitskevich
source share