Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. trait WithContext {
  2. fn with_context(&mut self, f: &mut FnMut(&mut Context<'_>));
  3.  
  4. fn with_context_once<'b>(&mut self, f: Box<dyn 'b + FnOnce(&mut Context<'_>)>);
  5. }
  6.  
  7. impl<'a> WithContext for Context<'a> {
  8. fn with_context(&mut self, f: &mut FnMut(&mut Context<'_>)) {
  9. f(self)
  10. }
  11.  
  12. fn with_context_once<'b>(&mut self, f: Box<dyn 'b + FnOnce(&mut Context<'_>)>) {
  13. f(self)
  14. }
  15. }
  16.  
  17. pub struct Context<'a> {
  18. parent: Option<&'a mut dyn WithContext>
  19. }
  20.  
  21. impl<'a> Context<'a> {
  22. fn child(&mut self) -> Context<'_> {
  23. Context {
  24. parent: Some(self),
  25. }
  26. }
  27.  
  28. pub fn with_parent<F: FnMut(&mut Context<'_>)>(&mut self, mut f: F) {
  29. if let Some(parent) = self.parent.as_mut() {
  30. parent.with_context(&mut f)
  31. }
  32. }
  33.  
  34. pub fn with_parent_once<F: FnOnce(&mut Context<'_>)>(&mut self, f: F) {
  35. if let Some(parent) = self.parent.as_mut() {
  36. parent.with_context_once(Box::new(f))
  37. }
  38. }
  39. }
  40.  
  41. fn this_doesnt_work(context: &mut Context) {
  42. let mut child = context.child();
  43.  
  44. let mut x : u32 = 0;
  45.  
  46. child.with_parent(|parent| {
  47. x = 0;
  48. });
  49.  
  50. let x = x;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement