Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. use std::thread;
  2. use std::time::Duration;
  3.  
  4. fn main() {
  5. let func = |num| {
  6. println!("calculating slowly...");
  7. thread::sleep(Duration::from_secs(2));
  8. num
  9. };
  10. let reference = &func;
  11. let mut expensive_result = Cacher::new(reference);
  12. println!("{}", expensive_result.value(1));
  13. }
  14.  
  15. struct Cacher<T>
  16. where
  17. T: Fn(u32) -> u32,
  18. {
  19. calculation: T,
  20. value: Option<u32>,
  21. }
  22.  
  23. impl<T> Cacher<T>
  24. where
  25. T: Fn(u32) -> u32,
  26. {
  27. fn new(calculation: T) -> Cacher<T> {
  28. Cacher {
  29. calculation,
  30. value: None,
  31. }
  32. }
  33.  
  34. fn value(&mut self, arg: u32) -> u32 {
  35. match self.value {
  36. Some(v) => v,
  37. None => {
  38. let v = (self.calculation)(arg);
  39. self.value = Some(v);
  40. v
  41. }
  42. }
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement