Skip to content

Instantly share code, notes, and snippets.

@charlespierce
Last active March 1, 2022 23:41
Show Gist options
  • Save charlespierce/e9b38ec0d6696b87b3a6d23334ff9faa to your computer and use it in GitHub Desktop.
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.
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