SHARE
TWEET

Untitled

a guest Aug 19th, 2019 59 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. pub struct Cache<F, V>
  2.     where F: FnOnce() -> V
  3. {
  4.     calculation_fn: Option<F>,
  5.     value: Option<V>,
  6. }
  7.  
  8. impl<F, V> Cache<F, V>
  9.     where F: FnOnce() -> V
  10. {
  11.     pub fn new(calculation: F) -> Cache<F, V> {
  12.         Cache {
  13.             calculation_fn: Some(calculation),
  14.             value: None,
  15.         }
  16.     }
  17.    
  18.     pub fn value(&mut self) -> &V {
  19.         self.value.get_or_insert_with(self.calculation_fn.take().unwrap())
  20.     }
  21. }
  22.  
  23. fn main() {
  24.     let mut counter = 0;
  25.     let mut sut = Cache::new(|| {
  26.         counter += 1;
  27.         42
  28.     });
  29.  
  30.     sut.value();
  31.     sut.value();
  32.  
  33.     assert_eq!(42, *sut.value());
  34.     assert_eq!(counter, 1);
  35. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top