Advertisement
mbazs

Rust traits

Nov 24th, 2017
535
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.47 KB | None | 0 0
  1. struct Cat {
  2.     name: &'static str,
  3.    stripes: bool,
  4.    age: u16
  5. }
  6.  
  7. struct Dog {
  8.    name: &'static str,
  9.     barks: bool,
  10.     age: u16
  11. }
  12.  
  13. trait Talkative {
  14.     fn say(&self) -> String;
  15. }
  16.  
  17. trait Aged {
  18.     fn age(&self) -> u16;
  19. }
  20.  
  21. impl Talkative for Cat {
  22.     fn say(&self) -> String {
  23.         String::from("miau!")
  24.     }
  25. }
  26.  
  27. impl Talkative for Dog {
  28.     fn say(&self) -> String {
  29.         String::from("vau!")
  30.     }
  31. }
  32.  
  33. impl Aged for Cat {
  34.     fn age(&self) -> u16 {
  35.         self.age
  36.     }
  37. }
  38.  
  39. impl Aged for Dog {
  40.     fn age(&self) -> u16 {
  41.         self.age
  42.     }
  43. }
  44.  
  45. fn say<T: Talkative>(t:&T) -> () {
  46.     println!("{}", t.say());
  47. }
  48.  
  49. fn older<'a, T: Aged>(a0: &'a T, a1: &'a T) -> &'a T {
  50.     if a0.age() > a1.age() {
  51.         a0
  52.     } else {
  53.         a1
  54.     }
  55. }
  56.  
  57. fn main() {
  58.     let animal0 = Cat { name: "Cirmi", stripes: false, age: 5 };
  59.     let animal1 = Cat { name: "Mirci", stripes: true,  age: 15 };
  60.     let o = older(&animal0, &animal1);
  61.     println!("Older cat says: '{}'", o.say()); // Why compiles? 'o' IS AN Aged but IS NOT A Talkative ...
  62.     // say(&o);     // this is better, it won't compile
  63.  
  64.     let animal0 = Dog { name: "Morzsa", barks: false, age: 6 };
  65.     let animal1 = Dog { name: "Benji", barks: true,  age: 8 };
  66.     let o = older(&animal0, &animal1);
  67.     println!("Older dog says: '{}'", o.say()); // Why compiles? 'o' IS AN Aged but IS NOT A Talkative ...
  68.     // say(&o);    // this is better, it won't compile
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement