20.10 Summary
Rust adopts many features associated with OOP (methods, controlled visibility, and polymorphism) but does so on its own terms:
- It does let you group data and methods (via
impl
blocks forstruct
s) and restrict access (through the module system and visibility). - Rust uses traits instead of classical inheritance, and trait objects (with dynamic dispatch) when runtime polymorphism is needed.
- Generics offer a powerful alternative to typical OOP-style inheritance for code reuse across multiple data types, often with better performance due to compile-time optimizations.
- For closed sets of types, consider an enum to avoid the extra overhead of dynamic dispatch and gain exhaustiveness checks.
- For open-ended sets of types, consider trait objects when flexibility is more important than compile-time optimizations.
- You cannot directly serialize a generic
Box<dyn SomeTrait>
because of runtime vtable pointers. Instead, consider enums or other patterns if you need to store heterogeneous data on disk.
By combining traits, generics, modules, and composition, Rust provides robust tools for building complex, maintainable software—without the fragility often associated with deep class hierarchies.