Hi guys, I'm a newbie to Rust,
there is a problem, which makes me struggled for 2 days:
I want to write a terminal application to print the Fibonacci sequence from 1 to N,
and I did it, after that, I want to add a cache to it, and here is the code:
use std::env;
use std::collections::HashMap;
fn main() {
let n = env::args().nth(1).expect("No n specify.");
let n: isize = n.parse()
.expect("N should be a number.");
let cache: &mut HashMap<String, String> = &mut HashMap::new();
println!("Input n: {}", n);
for i in 1 .. n + 1 {
println!("{}", fib(i, cache));
}
}
fn fib(n: isize, mut cache: &mut HashMap<String, String>) -> isize {
let key = n.to_string();
match cache.get(&key) {
Some(v) => {
let r: isize = v.parse()
.expect("Parse error");
r
},
None => {
let mut result;
if n == 0 {
result = 0;
} else if n == 1 || n == 2 {
result = 1;
} else {
result = fib(n - 1, cache) + fib(n - 2, cache);
}
cache.insert(key, result.to_string());
return result;
}
}
}
The code above has been modified many times because of the cache
's mutability remains incorrect.
how should I fix it?