20.3 OOP in Rust: No Classes or Inheritance
Rust does not have classical classes or inheritance. Instead, it offers:
- Structs and Enums: Flexible data types without hierarchical constraints.
- Traits: Similar to interfaces, traits specify method signatures (and can include default method bodies) without tying you to a single class hierarchy.
- Modules and Visibility: Rust's module system (with
pub
for public items and private by default) handles encapsulation. - Composition Over Inheritance: Combine multiple smaller structs or traits to achieve complex functionality rather than relying on extended class trees.
20.3.1 Code Reuse in Rust
In traditional OOP, inheritance is often used for code reuse. Rust encourages different patterns to accomplish the same goal:
- Traits: Allow you to define shared behavior that multiple types can implement.
- Generics: Enable you to write type-agnostic code that works across different data types.
- Composition: Build advanced functionality by combining small, focused structs or types.
- Modules: Group related code logically, re-exporting items as needed to share them across the codebase.
By using these features together, you can achieve significant code reuse without the pitfalls of rigid class hierarchies.