Guest User

Untitled

a guest
Oct 23rd, 2019
78
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. trait A: std::fmt::Debug {
  2. fn a(&self) {
  3. println!("Hello I'm {:?}", self);
  4. }
  5. }
  6.  
  7. #[derive(Debug)]
  8. struct B;
  9.  
  10. impl B {
  11. fn new() -> Self {
  12. println!("[Associated function] Creating B");
  13.  
  14. B
  15. }
  16.  
  17. fn observe_c(&self, _: &C) {
  18. println!("[Method] got C!");
  19. }
  20. }
  21.  
  22. impl A for B {}
  23.  
  24.  
  25. #[derive(Debug)]
  26. struct C;
  27.  
  28. impl C {
  29. fn new() -> Self {
  30. println!("[Associated function] Creating C");
  31.  
  32. C
  33. }
  34.  
  35. fn observe_b(&self, _: &B) {
  36. println!("[Method] got B!");
  37. }
  38. }
  39.  
  40. impl A for C {}
  41.  
  42.  
  43. fn static_dispatch<T: A>(value: &T) {
  44. print!("[Static dispatch] ");
  45. value.a();
  46. }
  47.  
  48. fn dynamic_dispatch(value: &dyn A) {
  49. print!("[Dynamic dispatch] ");
  50. value.a();
  51. }
  52.  
  53.  
  54.  
  55.  
  56. fn main() {
  57. let b = B::new();
  58. let c = C::new();
  59.  
  60. b.observe_c(&c);
  61. c.observe_b(&b);
  62.  
  63. static_dispatch(&b);
  64. static_dispatch(&c);
  65.  
  66. dynamic_dispatch(&b);
  67. dynamic_dispatch(&c);
  68. }
RAW Paste Data