我想用a HashMap来缓存一个依赖于地图中其他条目的昂贵计算.条目模式仅提供对匹配值的可变引用,但不提供对其余的引用HashMap.我非常感谢有关更好地解决这个(不正确的)玩具示例的反馈:
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied, Vacant};
fn compute(cache: &mut HashMap<u32, u32>, input: u32) -> u32 {
match cache.entry(input) {
Vacant(entry) => if input > 2 {
// Trivial placeholder for an expensive computation.
*entry.insert(compute(&mut cache, input - 1) +
compute(&mut cache, input - 2))
} else {
0
},
Occupied(entry) => *entry.get(),
}
}
fn main() {
let mut cache = HashMap::<u32, u32>::new();
let foo = compute(&mut cache, 12);
println!("{}", foo);
}
Run Code Online (Sandbox Code Playgroud)
(游乐场)
上面代码片段的问题是不 …