Guest User

Untitled

a guest
May 17th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.61 KB | None | 0 0
  1. struct Cacher<T, U>
  2. where T: Fn(U) -> U
  3. {
  4. calculation: T,
  5. value: Option<U>,
  6. }
  7.  
  8. impl<T, U> Cacher<T, U>
  9. where T: Fn(U) -> U
  10. {
  11. fn new(calculation: T) -> Cacher<T, U> {
  12. Cacher {
  13. calculation,
  14. value: None,
  15. }
  16. }
  17.  
  18. fn value(&mut self, arg: U) -> U {
  19. match self.value {
  20. Some(v) => v,
  21. None => {
  22. let v = (self.calculation)(arg);
  23. self.value = Some(v);
  24. v
  25. },
  26. }
  27. }
  28. }
  29.  
  30. fn main() {
  31. let mut cash = Cacher::new(|x| {x+1});
  32. println!("Hello, world! {}", cash.value(10));
  33. }
Add Comment
Please, Sign In to add comment