Guest User

Untitled

a guest
Mar 23rd, 2018
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. trait Animal {
  2. fn create(name: &'static str) -> Self;
  3.  
  4. fn name(&self) -> &'static str;
  5.  
  6. fn talk(&self) {
  7. println!("{} can't talk!", self.name());
  8. }
  9. }
  10.  
  11. struct Human {
  12. name: &'static str,
  13. }
  14.  
  15. impl Animal for Human {
  16. fn create(name: &'static str) -> Human {
  17. return Human { name: name };
  18. }
  19.  
  20. fn name(&self) -> &'static str {
  21. return self.name;
  22. }
  23.  
  24. fn talk(&self) {
  25. println!("{} says hello", self.name());
  26. }
  27. }
  28.  
  29. struct Cat {
  30. name: &'static str,
  31. }
  32.  
  33. impl Animal for Cat {
  34. fn create(name: &'static str) -> Cat {
  35. return Cat { name: name };
  36. }
  37.  
  38. fn name(&self) -> &'static str {
  39. return self.name;
  40. }
  41.  
  42. fn talk(&self) {
  43. println!("{} says meow", self.name());
  44. }
  45. }
  46.  
  47. // Generic trait
  48. trait Summable<T> {
  49. fn sum(&self) -> T;
  50. }
  51.  
  52. // add sum to any vector of i32 that returns an i32;
  53. impl Summable<i32> for Vec<i32> {
  54. fn sum(&self) -> i32 {
  55. let mut result: i32 = 0;
  56. for x in self {
  57. result += *x;
  58. }
  59. return result;
  60. }
  61. }
  62.  
  63. fn traits() {
  64. // let h = Human { name: "Chris" };
  65. // let h = Human::create("Chris");
  66. let h: Human = Animal::create("Chris");
  67. h.talk();
  68. let c = Cat { name: "Izembard" };
  69. c.talk();
  70.  
  71. // Add a trait to a type you do not own using generics
  72. let a = vec![1, 2, 3];
  73. println!("sum = {}", a.sum())
  74. }
  75.  
  76. fn main() {
  77. traits();
  78. }
Add Comment
Please, Sign In to add comment