我想实现一个斐波那契数列以及缓存已经计算的结果。我不确定这种方法在 Rust 中是否可行,但它是我想出的最好的。这是代码:
use std::collections::HashMap;
pub fn fib_hash(n: u32) -> u64 {
let mut map: HashMap<u32, u64> = HashMap::new();
// This is the engine which recurses saving each value in the map
fn f(map: &HashMap<u32, u64>, n: u32) -> u64 {
let c = match map.get(&n) {
Some(&number) => number,
_ => 0,
};
if c != 0 {
return c;
}
let m = match n {
1 if n < 1 => 0,
1...2 => 1,
_ => f(&map, n - 1) + f(&map, n - 2),
};
map.insert(n, m);
m
}
f(&map, n)
}
这个想法是有一个HashMap
可以重用的“全局”。但是,我猜这不太可能,因为我们最终会为地图提供多个可变借款人。这是我得到的错误
生锈 2015
error[E0596]: cannot borrow immutable borrowed content `*map` as mutable
--> src/lib.rs:20:9
|
7 | fn f(map: &HashMap<u32, u64>, n: u32) -> u64 {
| ------------------ use `&mut HashMap<u32, u64>` here to make mutable
...
20 | map.insert(n, m);
| ^^^ cannot borrow as mutable
生锈 2018
error[E0596]: cannot borrow `*map` as mutable, as it is behind a `&` reference
--> src/lib.rs:20:9
|
7 | fn f(map: &HashMap<u32, u64>, n: u32) -> u64 {
| ------------------ help: consider changing this to be a mutable reference: `&mut std::collections::HashMap<u32, u64>`
...
20 | map.insert(n, m);
| ^^^ `map` is a `&` reference, so the data it refers to cannot be borrowed as mutable
我可以在 Rust 中使用这种方法吗?这个问题的最佳解决方案是什么?