]>
Commit | Line | Data |
---|---|---|
e1599b0c XL |
1 | # Supertraits |
2 | ||
3 | Rust doesn't have "inheritance", but you can define a trait as being a superset | |
4 | of another trait. For example: | |
5 | ||
6 | ```rust,editable | |
7 | trait Person { | |
8 | fn name(&self) -> String; | |
9 | } | |
10 | ||
f035d41b | 11 | // Person is a supertrait of Student. |
e1599b0c XL |
12 | // Implementing Student requires you to also impl Person. |
13 | trait Student: Person { | |
14 | fn university(&self) -> String; | |
15 | } | |
16 | ||
17 | trait Programmer { | |
18 | fn fav_language(&self) -> String; | |
19 | } | |
20 | ||
f035d41b XL |
21 | // CompSciStudent (computer science student) is a subtrait of both Programmer |
22 | // and Student. Implementing CompSciStudent requires you to impl both supertraits. | |
e1599b0c XL |
23 | trait CompSciStudent: Programmer + Student { |
24 | fn git_username(&self) -> String; | |
25 | } | |
26 | ||
27 | fn comp_sci_student_greeting(student: &dyn CompSciStudent) -> String { | |
28 | format!( | |
29 | "My name is {} and I attend {}. My Git username is {}", | |
30 | student.name(), | |
31 | student.university(), | |
32 | student.git_username() | |
33 | ) | |
34 | } | |
35 | ||
36 | fn main() {} | |
37 | ``` | |
38 | ||
39 | ### See also: | |
40 | ||
41 | [The Rust Programming Language chapter on supertraits][trpl_supertraits] | |
42 | ||
43 | [trpl_supertraits]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-supertraits-to-require-one-traits-functionality-within-another-trait |