Hi,
I am working through The Rust Programming Language book and getting an error with compiling a test when I have implemented the generic version of the Cacher type:
error: lifetime may not live long enough
--> src\main.rs:78:37
|
78 | let mut c = Cacher::new(| a| a);
| -- ^ returning this value requires that `'1` must outlive `'2`
| ||
| |return type of closure is &'2 &i32
| has type `&'1 &i32`
error: aborting due to previous error
The type deceleration and test code:
use std::thread;
use std::time::Duration;
use std::collections::HashMap;
use std::hash::Hash;
use std::collections::hash_map::Entry;
use std::ops::Fn;
use std::cmp::Eq;
struct Cacher<T,U,V>
where
T: Fn(&U) -> V,
U: Hash + Eq + Clone,
V: Clone ,
{
calculation: T,
value: HashMap<U,V>,
}
impl<T,U,V> Cacher<T,U, V>
where
T: Fn(&U) -> V,
U: Hash + Eq + Clone,
V: Clone ,
{
fn new(calculation: T) -> Cacher<T,U,V> {
Cacher {
calculation ,
value: HashMap::new(),
}
}
fn value (&mut self, arg: U) -> &V {
match self.value.entry(arg) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
let v = (self.calculation)(entry.key());
entry.insert(v)
}
}
}
}
I have tried various changes for lifetimes in the new and value functions but so far no luck.
Any ideas?
Thanks,
Frank