I have data that can be divided into several categories and each category can divided into several sub-types. I save the data as HashMap<Type1, HashMap<Type2, Data>>
.
I need to get a mutable reference of different categories at the same time, so the definition becomes HashMap<Type1, RefCell<HashMap<Type2, Data>>>
.
How do I implement the get
function?
use std::cell::{RefCell, RefMut};
use std::collections::HashMap;
struct Foo<T> {
data: HashMap<u32, RefCell<HashMap<u32, T>>>,
}
impl<T> Foo<T> {
fn get_mut(&self, k: u32, k2: u32) -> Option<RefMut<T>> {
unimplemented!() // Help me >_<
}
}
The key question is when I call HashMap::get_mut
function on RefMut<HashMap<K,V>>
, it sees that there is not way to return Option<RefMut<V>>
use std::cell::RefMut;
use std::collections::HashMap;
//I can check twice if the map contains k, but it's inefficient.
fn get_mut<V>(map: RefMut<HashMap<u32, V>>, k: u32) -> Option<RefMut<V>> {
if map.contains_key(&k) {
Some(RefMut::map(map, |map| map.get_mut(&k).unwrap()))
} else {
None
}
}