父 trait

Rust 没有“继承”,但是您可以将一个 trait 定义为另一个 trait 的超集(即父 trait)。例如:

  1. trait Person {
  2. fn name(&self) -> String;
  3. }
  4. // Person 是 Student 的父 trait。
  5. // 实现 Student 需要你也 impl 了 Person。
  6. trait Student: Person {
  7. fn university(&self) -> String;
  8. }
  9. trait Programmer {
  10. fn fav_language(&self) -> String;
  11. }
  12. // CompSciStudent (computer science student,计算机科学的学生) 是 Programmer 和 Student 两者的子类。
  13. // 实现 CompSciStudent 需要你同时 impl 了两个父 trait。
  14. trait CompSciStudent: Programmer + Student {
  15. fn git_username(&self) -> String;
  16. }
  17. fn comp_sci_student_greeting(student: &dyn CompSciStudent) -> String {
  18. format!(
  19. "My name is {} and I attend {}. My favorite language is {}. My Git username is {}",
  20. student.name(),
  21. student.university(),
  22. student.fav_language(),
  23. student.git_username()
  24. )
  25. }
  26. fn main() {}

参见:

《Rust 程序设计语言》的“父级 trait”章节