如何在Ref <HashMap <K,V >>上调用get函数并返回Option <Ref <T >>?

我有可以分为几个类别的数据,每个类别可以分为几个子类型。我将数据另存为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
    }
}
sl0359 回答:如何在Ref <HashMap <K,V >>上调用get函数并返回Option <Ref <T >>?

似乎有一种方法可以完全满足您的期望,但是it was removed。但是,我认为这是他们可能没有考虑过的用例,因此尝试ping通该问题可能不是一个坏主意。

否则,这是一个效率不高的解决方案,将起作用:

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_entry(&self,k: u32,k2: u32) -> Option<RefMut<T>> {
        self.data
            .get(&k)
            .map(|inner| inner.borrow_mut())
            .filter(|x| x.contains_key(&k2))
            .map(|x| RefMut::map(x,|y| y.get_mut(&k2).unwrap()))
    }
}
本文链接:https://www.f2er.com/3165576.html

大家都在问