As suggested in Chapter 13, I am trying to implement the Cacher with a HashMap. Unlike some of the other questions asked, I am trying to follow the aproach taken by the author and use Option as value in the Cacher.
struct Cacher<T>
where T: Fn(u32) -> u32, //struct needs to know Type of closure(aka calc)
{
calc: T,
value: Option<HashMap<u32, u32>>
}
impl<T> Cacher<T>
where T: Fn(u32) -> u32,{
fn new(calculation: T) -> Cacher<T>{
Cacher {
calc: calculation,
value: None
}
}
fn value(&mut self, arg: u32) -> u32 {
match &mut self.value {
Some(map) => {
let v = map.entry(arg).or_insert((self.calc)(arg));
*v
},
None => {
let mut map = HashMap::new();
let v = map.insert(arg, (self.calc)(arg)).unwrap();
self.value = Some(map);
v
}
}
}
}
The code compiles but even running a simple:
let mut expensive_res = Cacher::new( |num| {
println!("calculating slowly....{}", num);
thread::sleep(Duration::from_secs(1));
num + 100
});
println!("{}", expensive_res.value(1));
I get an Panic when running it.
thread 'main' panicked at 'called Option::unwrap()
on a None
value'.
Any suggestions? Why is unwrap here a None?
Many thanks