minigrep_study/example/
closure.rs1use std::{hash::Hash, collections::HashMap};
2
3pub struct Cacher<T,K,V>
4 where
5 T: Fn(K) -> V,
6 K: Hash + Eq,
7 V: Copy,
8{
9 calculation: T,
10 value: HashMap<K,V>,
11}
12
13impl<T,K,V> Cacher<T,K,V>
14 where
15 T: Fn(K) -> V,
16 K: Hash + Eq + Copy,
17 V: Copy
18{
19 pub fn new(calculation: T) -> Cacher<T,K,V> {
20 let value: HashMap<K,V> = HashMap::new();
21 Cacher {
22 calculation,
23 value,
24 }
25 }
26
27 pub fn value(&mut self, arg: K) -> V {
28 match self.value.get(&arg) {
30 Some(v) => *v,
31 None => {
32 let v = (self.calculation)(arg);
33 self.value.insert(arg, v);
34 v
35 },
36 }
37 }
38}
39
40#[cfg(test)]
41mod tests {
42 use super::*;
43
44 #[test]
45 fn call_with_different_values() {
46 let mut c = Cacher::new(|a| a);
47 let mut c2 = Cacher::new(|a: &str| a);
48
49 let v1 = c.value(1);
50 let s = "hello";
51 let v2 = c2.value(&s[..]);
52 let v3 = c.value(2);
53
54 assert_eq!(v1, 1);
55 assert_eq!(v2, "hello");
56 assert_eq!(v3, 2);
57 }
58}
59