Last active: 2 years ago
use std::fmt::{Debug, Formatter};
struct Cache<T, E>
where
T: Fn(E) -> E,
E: Clone + Debug,
{
query: T,
value: Option<E>,
}
impl<T, E> Cache<T, E>
where
T: Fn(E) -> E,
E: Clone + Debug,
{
fn new(query: T) -> Self {
Self { query, value: None }
}
fn value(&mut self, arg: E) -> E {
match &self.value {
Some(v) => v.clone(),
None => {
let v = (self.query)(arg);
self.value = Some(v.clone());
v
}
}
}
}
impl<T, E> Debug for Cache<T, E>
where
T: Fn(E) -> E,
E: Clone + Debug,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
if let Some(v) = &self.value {
writeln!(f, "{:?}", v.clone()).expect("TODO: panic message");
}
Ok(())
}
}
fn main() {
let mut cache = Cache::new(|item: i32| item * 2);
println!("{:?}", cache);
println!("{:?}", cache.value(3));
println!("{:?}", cache);
}