我有可以分为几个类别的数据,每个类别可以分为几个子类型。我将数据另存为HashMap<Type1,HashMap<Type2,Data>>
。
我需要同时获取不同类别的可变引用,因此定义变为HashMap<Type1,RefCell<HashMap<Type2,Data>>>
。
如何实现get
函数?
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 >_<
}
}
关键问题是,当我在HashMap::get_mut
上调用RefMut<HashMap<K,V>>
函数时,它发现无法返回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
}
}