You've already forked comprehensive-rust
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:
committed by
GitHub
parent
d0656ca90b
commit
ac2cb44d54
@ -1,5 +1,5 @@
|
||||
---
|
||||
minutes: 10
|
||||
minutes: 15
|
||||
---
|
||||
|
||||
# Traits
|
||||
|
@ -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
|
||||
|
41
src/methods-and-traits/traits/supertraits.md
Normal file
41
src/methods-and-traits/traits/supertraits.md
Normal 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>
|
Reference in New Issue
Block a user