NLinker

Dynamic dispatch in Rust

Oct 3rd, 2017 (edited)
195
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // https://play.rust-lang.org/?gist=e542126c32b831afedd29efb950c9e29
  2. // https://imgur.com/a/osZgl :-)
  3.  
  4. trait Animal {
  5.     fn sound(&self);
  6. }
  7.  
  8. #[derive(Debug)]
  9. enum Color {
  10.     White,
  11.     Black,
  12.     Grey,
  13. }
  14.  
  15. struct Cat {
  16.     color: Color,
  17. }
  18. impl Animal for Cat {
  19.     fn sound(&self) { println!("Meow: {:?}", self.color) }
  20. }
  21.  
  22.  
  23. struct Dog {
  24.     kind: i32,
  25. }
  26. impl Animal for Dog {
  27.     fn sound(&self) { println!("Wuff: {}", self.kind) }
  28. }
  29.  
  30. fn main() {
  31.     let cat1 = Cat { color: Color::White };
  32.     let cat2 = Cat { color: Color::Black };
  33.     let cat3 = Cat { color: Color::Grey };
  34.     let dog = Dog { kind: 2 };
  35.     let animals: Vec<&dyn Animal> = vec![&cat1, &cat2, &cat3, &dog];
  36.     for animal in animals {
  37.         animal.sound();
  38.     }
  39. }
RAW Paste Data