Last active
May 21, 2019 05:57
-
-
Save mrotaru/e39a7319bad3aafabab4182ed4873da9 to your computer and use it in GitHub Desktop.
Mutable borrow - https://stackoverflow.com/q/56181266/447661
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
use std::collections::HashMap; | |
struct Cacher<T> | |
where | |
T: Fn(&u32) -> u32, | |
{ | |
calculation: T, | |
values: HashMap<u32, u32>, | |
} | |
impl<T> Cacher<T> | |
where | |
T: Fn(&u32) -> u32, | |
{ | |
fn new(calculation: T) -> Cacher<T> { | |
Cacher { | |
calculation, | |
values: HashMap::new(), | |
} | |
} | |
fn value(&mut self, arg: u32) -> &u32 { | |
let values = &mut self.values; | |
match values.get(&arg) { | |
Some(v) => &v, | |
None => { | |
let v = (self.calculation)(&arg); | |
values.insert(arg, v); | |
&values.get(&arg).unwrap() | |
} | |
} | |
} | |
} | |
#[test] | |
fn call_with_different_values() { | |
let mut c = Cacher::new(|a| a + 1); | |
let v1 = c.value(1); | |
assert_eq!(*v1, 2); | |
let v2 = c.value(2); | |
assert_eq!(*v2, 3); | |
} | |
fn main {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment