Last active
March 1, 2022 23:41
-
-
Save charlespierce/e9b38ec0d6696b87b3a6d23334ff9faa to your computer and use it in GitHub Desktop.
Example of using a RefCell to cache intermediate results without needing mutable access.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct FibonacciCalculator { | |
cache: RefCell<HashMap<usize, usize>>, | |
} | |
impl FibonacciCalculator { | |
/// Calculate the Nth fibonacci number, caching the result to prevent recalculation | |
/// Note that this takes `&self`, not `&mut self`! | |
fn calculate(&self, n: usize) -> usize { | |
// Base case | |
if n <= 2 { | |
return 1; | |
} | |
// Check the cache | |
if let Some(value) = self.cache.borrow().get(&n) { | |
return *value; | |
} | |
// Calculate and cache the value | |
let result = self.calculate(n - 1) + self.calculate(n - 2); | |
self.cache.borrow_mut().insert(n, result); | |
result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment