Rounding off traits
This has been a large topic, but we have two more aspects to consider for traits: inheritance and deriving. One that should be familiar if you're used to any form of object-oriented programming.
Inheritance
This is very similar to inheritance within C++ and C#:
trait One { fn one(&self); } trait OneTwo : One { fn onetwo(&self); }
Note
Code for this part is in 09/inheritance
.
The code that implements OneTwo
must also implement One
(the same as when we overrode the default method, we still had to define is_done
), therefore:
struct Three; impl One for Three { fn one(&self) { println!("one"); } } impl OneTwo for Three { fn onetwo(&self) { println!("onetwo"); } }
And the result is as follows:

If we omitted the impl One
block, we would get a compilation error complaining that impl OneTwo
requires impl One
to exist.
Deriving
Rust provides a handy attribute that allows you to access a number of commonly used traits without having to implement...