Traits

A trait is a collection of methods defined for an unknown type:
Self. They can access other methods declared in the same trait.

Traits can be implemented for any data type. In the example below,
we define Animal, a group of methods. The Animal trait is
then implemented for the Sheep data type, allowing the use of
methods from Animal with a Sheep.

  1. struct Sheep { naked: bool, name: &'static str }
  2. trait Animal {
  3. // Static method signature; `Self` refers to the implementor type.
  4. fn new(name: &'static str) -> Self;
  5. // Instance method signatures; these will return a string.
  6. fn name(&self) -> &'static str;
  7. fn noise(&self) -> &'static str;
  8. // Traits can provide default method definitions.
  9. fn talk(&self) {
  10. println!("{} says {}", self.name(), self.noise());
  11. }
  12. }
  13. impl Sheep {
  14. fn is_naked(&self) -> bool {
  15. self.naked
  16. }
  17. fn shear(&mut self) {
  18. if self.is_naked() {
  19. // Implementor methods can use the implementor's trait methods.
  20. println!("{} is already naked...", self.name());
  21. } else {
  22. println!("{} gets a haircut!", self.name);
  23. self.naked = true;
  24. }
  25. }
  26. }
  27. // Implement the `Animal` trait for `Sheep`.
  28. impl Animal for Sheep {
  29. // `Self` is the implementor type: `Sheep`.
  30. fn new(name: &'static str) -> Sheep {
  31. Sheep { name: name, naked: false }
  32. }
  33. fn name(&self) -> &'static str {
  34. self.name
  35. }
  36. fn noise(&self) -> &'static str {
  37. if self.is_naked() {
  38. "baaaaah?"
  39. } else {
  40. "baaaaah!"
  41. }
  42. }
  43. // Default trait methods can be overridden.
  44. fn talk(&self) {
  45. // For example, we can add some quiet contemplation.
  46. println!("{} pauses briefly... {}", self.name, self.noise());
  47. }
  48. }
  49. fn main() {
  50. // Type annotation is necessary in this case.
  51. let mut dolly: Sheep = Animal::new("Dolly");
  52. // TODO ^ Try removing the type annotations.
  53. dolly.talk();
  54. dolly.shear();
  55. dolly.talk();
  56. }