Created
November 14, 2019 18:43
-
-
Save Megaprog/72d84a8ac508779ff212a8b6053e23f2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::{Arc, Mutex, MutexGuard}; | |
use std::collections::HashMap; | |
use std::ops::Deref; | |
pub struct Inner<'a>(MutexGuard<'a, HashMap<i32, Vec<i32>>>, i32); | |
impl<'a> Deref for Inner<'a> { | |
type Target = Vec<i32>; | |
fn deref(&self) -> &Self::Target { | |
self.0.get(&self.1).unwrap() | |
} | |
} | |
pub struct MyStruct { | |
data: Arc<Mutex<HashMap<i32, Vec<i32>>>>, | |
} | |
impl MyStruct { | |
pub fn get_data_for<'a>(&'a self, i: i32) -> Inner<'a> { | |
let d = self.data.lock().unwrap(); | |
Inner(d, i) | |
} | |
} | |
fn main() { | |
let mut hm = HashMap::new(); | |
hm.insert(1, vec![1,2,3]); | |
let s = MyStruct { | |
data: Arc::new(Mutex::new(hm)) | |
}; | |
{ | |
let v = s.get_data_for(1); | |
println!("{:?}", *v); | |
let x : Vec<_> = v.iter().map(|x| x * 2).collect(); | |
println!("{:?}", x); // Just an example to see that it works | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment