实现 Unsafe Trait

  1. trait Pet {
  2. fn talk(&self) -> String;
  3. fn greet(&self) {
  4. println!("Oh you're a cutie! What's your name? {}", self.talk());
  5. }
  6. }
  7. struct Dog {
  8. name: String,
  9. age: i8,
  10. }
  11. impl Pet for Dog {
  12. fn talk(&self) -> String {
  13. format!("Woof, my name is {}!", self.name)
  14. }
  15. }
  16. fn main() {
  17. let fido = Dog { name: String::from("Fido"), age: 5 };
  18. fido.greet();
  19. }
  • To implement Trait for Type, you use an impl Trait for Type { .. } block.

  • Unlike Go interfaces, just having matching methods is not enough: a Cat type with a talk() method would not automatically satisfy Pet unless it is in an impl Pet block.

  • Traits may provide default implementations of some methods. Default implementations can rely on all the methods of the trait. In this case, greet is provided, and relies on talk.