Advertisement
Guest User

Untitled

a guest
Apr 25th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. #![feature(fnbox)]
  2. use std::boxed::FnBox;
  3.  
  4. struct TaskRunner<'a> {
  5. cb: Option<Box<FnBox() + 'a>>,
  6. }
  7.  
  8. impl<'a> TaskRunner<'a> {
  9. fn new() -> Self { TaskRunner { cb: None } }
  10.  
  11. fn start_task(&mut self, cb: Box<FnBox() + 'a>) {
  12. self.cb = Some(cb);
  13. }
  14.  
  15. fn finish_task(&mut self) {
  16. if let Some(cb) = self.cb.take() {
  17. cb.call_box(());
  18. }
  19. }
  20. }
  21.  
  22. struct Manager<'a> {
  23. task_runner: TaskRunner<'a>,
  24. }
  25.  
  26. impl<'a> Manager<'a> {
  27. fn new() -> Self {
  28. Manager {
  29. task_runner: TaskRunner::new(),
  30. }
  31. }
  32.  
  33. fn do_next_thing(&self) {
  34. println!("Task finished! Going to do the next thing!");
  35. }
  36.  
  37. fn run_task(&mut self) {
  38. self.task_runner.start_task(Box::new(|| {
  39. println!("Finished!");
  40. // The following does not compile - how are we even going to use the callback?
  41. self.do_next_thing();
  42. } ));
  43. self.task_runner.finish_task();
  44. }
  45. }
  46.  
  47. fn main() {
  48. let mut manager = Manager::new();
  49. manager.run_task();
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement