Advertisement
NLinker

Dynamic dispatch in Rust

Oct 3rd, 2017 (edited)
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 0.80 KB | None | 0 0
  1. // https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=8fb2d746bd9e13e735dcfc5cef97713f
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement