Supertraits / Trait Dependencies
Traits can be extended by new traits.
#![allow(unused)] fn main() { pub trait DeviceId { /* trait for device ID types */ } pub trait GraphicsDevice: DeviceId { /* Graphics device specifics */ } // From stdlib pub trait Ord: PartialOrd { /* methods for Ord */ } }
-
When authoring a trait, you can specify traits that a type must also. These are called Supertraits.
For the example above, any type that implements
GraphicsDevicemust also implementDeviceId. -
These hierarchies of traits let us design systems around the behavior of complex real-world taxonomies (like machine hardware, operating system specifics).
-
This is distinct from object inheritance! But it looks similar.
-
Object inheritance allows for overrides and brings in the behavior of the inherited types by default.
-
A trait having a supertrait doesn’t mean that trait can override method implementations as default implementations.
-
ref:
- https://doc.rust-lang.org/reference/items/traits.html?highlight=supertrait#r-items.traits.supertraits