]> git.proxmox.com Git - rustc.git/blame - src/doc/rust-by-example/src/trait/supertraits.md
New upstream version 1.46.0~beta.2+dfsg1
[rustc.git] / src / doc / rust-by-example / src / trait / supertraits.md
CommitLineData
e1599b0c
XL
1# Supertraits
2
3Rust doesn't have "inheritance", but you can define a trait as being a superset
4of another trait. For example:
5
6```rust,editable
7trait 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.
13trait Student: Person {
14 fn university(&self) -> String;
15}
16
17trait 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
23trait CompSciStudent: Programmer + Student {
24 fn git_username(&self) -> String;
25}
26
27fn 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
36fn 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