I'm going through the book again, since I'm a bit rusty on Rust
I'm at chapter 3 now and I've implemented a function to calculate the nth Fibonacci number. To test, I run a loop from 1 to 99 and calculate the Fibonacci term at each number. I want it to memoize the values, because currently it is getting slow at about n = 40 because it's doing the work of calculating all terms down to term 1 each time.
I want to save the nth Fibonacci term in a hashmap with key = n and value = Fib(n) and first check my map before calculating all the terms down to term 1 again.
However, the map would need to be declared in a scope bigger than that of the function. This is now my problem. What is the best way of achieving that? static mut
? I know that's not very popular here for good reason. static RefCell
? Anything else?
My fibonacci function for reference:
fn fibonacci(n: usize) -> u128 {
if n == 1 {
1
} else if n == 2 {
1
} else {
fibonacci(n - 1) + fibonacci(n - 2)
}
}