1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-07-13 17:44:20 +02:00

Cover Supertraits, Generic Traits (#1854)

This commit is contained in:
Dustin J. Mitchell
2024-03-12 09:49:39 -04:00
committed by GitHub
parent d0656ca90b
commit ac2cb44d54
5 changed files with 97 additions and 2 deletions

View File

@ -1,5 +1,5 @@
---
minutes: 10
minutes: 15
---
# Traits

View File

@ -1,6 +1,6 @@
# Associated Types
Associated types are placeholder types which are filled in by the trait
Associated types are placeholder types which are supplied by the trait
implementation.
```rust,editable

View File

@ -0,0 +1,41 @@
# Supertraits
A trait can require that types implementing it also implement other traits,
called _supertraits_. Here, any type implementing `Pet` must implement `Animal`.
```rust,editable
trait Animal {
fn leg_count(&self) -> u32;
}
trait Pet: Animal {
fn name(&self) -> String;
}
struct Dog(String);
impl Animal for Dog {
fn leg_count(&self) -> u32 {
4
}
}
impl Pet for Dog {
fn name(&self) -> String {
self.0.clone()
}
}
fn main() {
let puppy = Dog(String::from("Rex"));
println!("{} has {} legs", puppy.name(), puppy.leg_count());
}
```
<details>
This is sometimes called "trait inheritance" but students should not expect this
to behave like OO inheritance. It just specifies an additional requirement on
implementations of a trait.
<details>