相关疑难解决方法(0)

如何将*可选*引用返回到 RefCell 内容中

我有一个类型,将其数据存储在 a 后面的容器中Rc<RefCell<>>,该容器大部分对公共 API 是隐藏的。例如:

struct Value;

struct Container {
    storage: Rc<RefCell<HashMap<u32, Value>>>,
}

impl Container {
    fn insert(&mut self, key: u32, value: Value) {
        self.storage.borrow_mut().insert(key, value);
    }

    fn remove(&mut self, key: u32) -> Option<Value> {
        self.storage.borrow_mut().remove(&key)
    }

    // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,查看容器内部需要返回Ref. 这可以通过使用来实现Ref::map()- 例如:

// peek value under key, panicking if not present
fn peek_assert(&self, key: u32) -> Ref<'_, Value> {
    Ref::map(self.storage.borrow(), |storage| storage.get(&key).unwrap())
}
Run Code Online (Sandbox Code Playgroud)

但是,我想要一个非恐慌版本的peek,它会返回Option<Ref<'_, Value>>。这是一个问题,因为Ref::map要求您返回对 内存在的内容的引用 …

rust refcell

8
推荐指数
1
解决办法
1034
查看次数

标签 统计

refcell ×1

rust ×1