Answer#
There is no class Dog : Animal. Three tools replace it, and each is the right choice in a different situation. The answers below show each as its own complete example; all three compiled and ran with rustc 1.93.0.
| You want | Use |
|---|---|
| Different types with the same operations, and new types may be added later | a trait |
| A fixed, known set of variants | an enum |
| To reuse the code and data of another type | composition: hold it as a field |
Common mistakes#
- Looking for a base-class field to inherit. Traits have no fields; put shared data in a struct and share it by composition.
- Using
Box<dyn Trait>when an enum would do. Enums are simpler and letmatchcheck that every case is handled. - Copying a class hierarchy of five levels. Flatten it: most levels existed only to share code.
Related questions#
Can a trait have default method bodies?#
Yes. A default method works like a virtual method with a body, and each type can override it.
What is the difference between dyn Trait and a generic T: Trait?#
A generic is resolved at compile time and produces code for each type. dyn Trait is resolved at run time through a vtable and lets one collection hold different types.
Sources#
- The Rust Book, "Traits: Defining Shared Behavior": https://doc.rust-lang.org/book/ch10-02-traits.html
- The Rust Book, "Object-Oriented Programming Features of Rust": https://doc.rust-lang.org/book/ch18-00-oop.html