Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.80 KB | None | 0 0
  1. #[derive(Debug)]
  2. struct A {
  3. x: i32,
  4. }
  5.  
  6. #[derive(Debug)]
  7. struct B {
  8. c: char,
  9. }
  10.  
  11. trait Foo {
  12. fn foo(&mut self);
  13. }
  14.  
  15. impl Foo for A {
  16. fn foo(&mut self) {
  17. self.x = 5;
  18. }
  19. }
  20.  
  21. impl Foo for B {
  22. fn foo(&mut self) {
  23. self.c = 'F';
  24. }
  25. }
  26.  
  27. fn do_same_thing_static_dispatch(f: &mut impl Foo) {
  28. println!("Doing something...");
  29. f.foo();
  30. println!("Doing something else...");
  31. }
  32.  
  33. fn do_same_thing_dynamic_dispatch(f: &mut dyn Foo) {
  34. println!("Doing something...");
  35. f.foo();
  36. println!("Doing something else...");
  37. }
  38.  
  39. fn main() {
  40. let mut a = A { x: 0 };
  41. let mut b = B { c: 'a' };
  42. do_same_thing_static_dispatch(&mut a);
  43. do_same_thing_static_dispatch(&mut b);
  44. do_same_thing_dynamic_dispatch(&mut a);
  45. do_same_thing_dynamic_dispatch(&mut b);
  46. dbg!(a, b);
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement