Red*_*ctk 2 hashmap ownership rust
我正在努力寻找一种优雅的解决方案来访问 Rust 中的嵌套地图以实现只读目的。我有这种情况,理想情况下,作为示例,我可以返回对空映射的引用(这当然不起作用,因为空哈希映射由函数拥有):
struct S {
stuff: HashMap<A, HashMap<B, C>>
}
impl S {
fn get(&self, a: &A) -> &HashMap<B,C> {
return self.stuff.get(a).unwrap_or(&HashMap::new());
}
}
Run Code Online (Sandbox Code Playgroud)
无法保证地图内容将具有键 a,因此必须处理可选性。
我希望解决方案以有效的方式(无副本/移动)实现使用此或类似签名的方法 get ,因为地图内容可能非常大。
我只能想到以下解决方案,但我认为一定有更直接的解决方案:
在我看来,解决方案(3)是实现上述目标的最佳方法,但也许我遗漏了一些东西,并且有更直接的方法?
返回Option<&HashMap>是惯用且简单的。
fn get(&self, a: &A) -> Option<&HashMap<B,C>> {
self.stuff.get(a)
}
Run Code Online (Sandbox Code Playgroud)
您可以用 做的任何事情都&HashMap可以用 来完成Option<&HashMap>。例如,您可以检查密钥是否存在。
if s.get(&a).map_or(false, |hm| hm.contains_key(&b)) {
println!("key exists");
}
Run Code Online (Sandbox Code Playgroud)
这会false在getreturns时产生,这与调用空值None相同。contains_keyHashMap
作为奖励,Option包含引用的 始终在内存中与引用大小相同。
| 归档时间: |
|
| 查看次数: |
148 次 |
| 最近记录: |