Replacing Inheritance Hierarchies
local graph
Chapter 12 — Replacing Inheritance Hierarchies
Section titled “Chapter 12 — Replacing Inheritance Hierarchies”Novus ordo seclorum. (A new order of the ages.)
Object-oriented programming centers on the class hierarchy. A Shape base class with Circle and Rectangle subclasses. An Animal hierarchy with Mammal and Bird branches. An Employee class with Manager and Engineer specializations. These hierarchies pervade OOP education, design patterns, and production codebases. They express both shared behavior (methods inherited from parent classes) and the “is-a” relationship (a Circle is a Shape, a Manager is an Employee).
Rust has no inheritance. There is no extends keyword, no base class, no protected members, no override annotations. A struct cannot inherit fields or methods from another struct. This absence is not an oversight or a feature awaiting implementation. It reflects a deliberate design choice rooted in decades of experience with inheritance’s costs.
This chapter explores why Rust omits inheritance, what problems that decision solves, and how to achieve the goals that inheritance served using Rust’s tools: composition, traits, and enums. The transition requires rethinking familiar patterns, but the resulting designs are often clearer, more flexible, and easier to maintain.
Why Rust has no inheritance
Inheritance conflates several distinct concepts. Code reuse: child classes gain parent methods without rewriting them. Interface conformance: subclasses fulfill parent contracts. Subtyping: a subclass instance can substitute for a parent instance. Runtime polymorphism: virtual method dispatch selects implementations based on concrete type. These capabilities are useful, but bundling them in a single mechanism creates problems that become apparent in large codebases.
The fragile base class problem emerges when modifying a base class breaks subclasses in unexpected ways. Adding a method to a base class might conflict with a method in a subclass. Changing the implementation of a base method might violate assumptions that subclasses depend on. The more subclasses exist, the more dangerous base class changes become. Inheritance creates implicit coupling that grows increasingly difficult to manage.
Deep inheritance hierarchies compound these problems. A class inheriting from a class inheriting from another class inherits all their accumulated complexity. Understanding behavior requires tracing through multiple levels. Method resolution becomes non-obvious when overrides exist at multiple levels. The “yo-yo problem” describes the experience of bouncing between parent and child classes while trying to understand a single method call, an activity that has caused more IDE tab explosions than any other known phenomenon in software development.
Multiple inheritance introduces further complications. The diamond problem occurs when a class inherits from two classes that share a common ancestor, creating ambiguity about which inherited implementation to use. Languages handle this differently: C++ requires explicit disambiguation, Python uses method resolution order algorithms, and Java and C# prohibit multiple class inheritance entirely (allowing only multiple interface implementation).
Inheritance also encourages modeling that prioritizes taxonomy over behavior. Deciding whether a Penguin should inherit from Bird (penguins are birds) or create an exception for the fly method leads to awkward workarounds. Countless whiteboard sessions have been consumed by debates over whether a Square is a Rectangle, typically resolved only when someone notices the meeting has run forty minutes over. Real-world entities resist clean hierarchical classification. The resulting hierarchies often reflect initial design assumptions that become obstacles as requirements evolve.
Rust sidesteps these problems by not offering inheritance. Instead, it provides mechanisms that address the legitimate needs inheritance serves, each targeted at a specific concern. Composition addresses code reuse. Traits address interface conformance and polymorphism. Enums address closed sets of variants. These mechanisms combine flexibly without the coupling that inheritance imposes.
Composition over inheritance
The “composition over inheritance” principle predates Rust. The Gang of Four’s design patterns book, published in 1994, recommends favoring composition. Object-oriented languages support composition, but inheritance remains the default tool because it requires less explicit wiring. In Rust, composition is the only option, which turns out to be an advantage.
Composition means building types that contain other types as fields, delegating behavior to those contained types. Instead of a Car inheriting from Vehicle, a Car contains an Engine, Wheels, and other components. The car delegates engine-related behavior to its engine field rather than inheriting engine methods.
Consider modeling document elements that can be styled. An object-oriented approach might define a base StyledElement class with styling properties and methods, then have Paragraph, Heading, and List inherit from it. The inheritance approach in pseudocode:
abstract class StyledElement { protected Style style; public void applyStyle(Style s) { this.style = s; } public Style getStyle() { return this.style; }}
class Paragraph extends StyledElement { private String text; // Paragraph-specific methods}
class Heading extends StyledElement { private String text; private int level; // Heading-specific methods}The Rust approach uses composition. Each element type contains a Style rather than inheriting from a styled base:
pub struct Style { pub font_size: u16, pub color: String, pub bold: bool,}
pub struct Paragraph { pub text: String, pub style: Style,}
pub struct Heading { pub text: String, pub level: u8, pub style: Style,}
impl Paragraph { pub fn apply_style(&mut self, style: Style) { self.style = style; }}
impl Heading { pub fn apply_style(&mut self, style: Style) { self.style = style; }}The composition approach requires implementing apply_style on each type rather than inheriting it once. This duplication concerns developers accustomed to inheritance’s code sharing. Several observations address this concern.
The duplicated code is minimal. Each implementation is a single line. In inheritance-based designs, the shared code is often similarly trivial, with inheritance’s machinery providing little actual savings.
Traits can capture the shared interface. A Styleable trait defines the contract that styled elements fulfill. Types implement the trait, enabling generic code that works with any styled element:
pub trait Styleable { fn apply_style(&mut self, style: Style); fn style(&self) -> &Style;}
impl Styleable for Paragraph { fn apply_style(&mut self, style: Style) { self.style = style; } fn style(&self) -> &Style { &self.style }}
impl Styleable for Heading { fn apply_style(&mut self, style: Style) { self.style = style; } fn style(&self) -> &Style { &self.style }}Macros can reduce the boilerplate when many types need identical implementations. A derive macro could generate Styleable implementations for types with a style field. This is explicit code generation rather than implicit inheritance, making the mechanism visible and controllable.
The composition approach provides flexibility that inheritance lacks. A type can contain multiple components with independent lifecycles. An element might have both a Style and a Layout, each managed separately. Adding animation capabilities later requires only adding an Animation field, not restructuring an inheritance hierarchy. Components can be replaced at runtime; a Paragraph could receive a different Style without changing its type.
The following diagram contrasts inheritance and composition for the styled elements example:
graph LR
subgraph INH["Inheritance Approach"]
SE["StyledElement<br/>- style: Style<br/>+ applyStyle()"]
P1["Paragraph<br/>- text: String"]
H1["Heading<br/>- text: String<br/>- level: int"]
SE --> P1
SE --> H1
end
subgraph COMP["Composition Approach"]
ST["Style<br/>- fontSize: u16<br/>- color: String"]
P2["Paragraph<br/>- text: String<br/>- style: Style"]
H2["Heading<br/>- text: String<br/>- level: u8<br/>- style: Style"]
ST -. contains .-> P2
ST -. contains .-> H2
end
[!visual-conversion] Inheritance creates a hierarchy; composition embeds shared components. Print UML-style diagram (PDF 305, printed p. 299) of two stacked frames, recreated in Mermaid; class boxes, members and the “contains” labels verbatim (the composition edges are dotted in print).
Trait hierarchies as capability contracts
When object-oriented inheritance serves primarily to define interfaces (rather than share implementation), traits provide a direct translation. A trait hierarchy can express the same relationships as an interface hierarchy, with additional flexibility in how implementations are organized.
Consider a drawing application with shapes that can be drawn, measured, and transformed. An object-oriented design might use:
interface Drawable { void draw(Canvas canvas);}
interface Measurable { double area(); double perimeter();}
interface Shape extends Drawable, Measurable { void transform(Matrix m);}The Rust equivalent uses trait hierarchies. A trait can require other traits as prerequisites (supertraits), expressing capability dependencies:
pub trait Drawable { fn draw(&self, canvas: &mut Canvas);}
pub trait Measurable { fn area(&self) -> f64; fn perimeter(&self) -> f64;}
pub trait Shape: Drawable + Measurable { fn transform(&mut self, matrix: &Matrix);}Any type implementing Shape must also implement Drawable and Measurable. The trait hierarchy expresses that shapes are drawable and measurable, a capability relationship rather than a taxonomic one.
Implementing these traits for concrete types:
pub struct Circle { pub center: Point, pub radius: f64,}
impl Drawable for Circle { fn draw(&self, canvas: &mut Canvas) { canvas.draw_circle(self.center, self.radius); }}
impl Measurable for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius } fn perimeter(&self) -> f64 { 2.0 * std::f64::consts::PI * self.radius }}
impl Shape for Circle { fn transform(&mut self, matrix: &Matrix) { self.center = matrix.apply(self.center); self.radius *= matrix.scale_factor(); }}Unlike inheritance hierarchies, trait implementations are independent. Nothing forces Circle to implement all three traits together. If a context needs only Drawable, it can work with types implementing only that trait. The granularity enables precise capability requirements without forcing types into hierarchies that bundle unrelated capabilities.
Functions accepting trait bounds express exactly what capabilities they need:
fn render<T: Drawable>(shape: &T, canvas: &mut Canvas) { shape.draw(canvas);}fn describe<T: Measurable>(shape: &T) -> String { format!("Area: {:.2}, Perimeter: {:.2}", shape.area(), shape.perimeter())}
fn process<T: Shape>(shape: &mut T, canvas: &mut Canvas, matrix: &Matrix) { shape.transform(matrix); shape.draw(canvas);}This flexibility has no equivalent in class hierarchies. An object-oriented design might create intermediate interfaces or use multiple inheritance to achieve similar granularity, but the result is typically more complex and less discoverable.
Enum-based polymorphism
When the set of variants is known and closed, enums provide polymorphism without traits or dynamic dispatch. An enum with variants for each case allows pattern matching to handle each variant explicitly, with the compiler ensuring exhaustive coverage.
Consider modeling payment methods: credit card, bank transfer, and digital wallet. The inheritance approach defines a PaymentMethod base class with subclasses for each type. The Rust approach uses an enum:
pub enum PaymentMethod { CreditCard { number: String, expiry: String, cvv: String, }, BankTransfer { account: String, routing: String, }, DigitalWallet { provider: String, token: String, },}
impl PaymentMethod { pub fn process(&self, amount: u64) -> Result<Receipt, PaymentError> { match self { PaymentMethod::CreditCard { number, expiry, cvv } => { // Credit card processing logic Ok(Receipt::new("card", amount)) } PaymentMethod::BankTransfer { account, routing } => { // Bank transfer logic Ok(Receipt::new("bank", amount)) } PaymentMethod::DigitalWallet { provider, token } => { // Digital wallet logic Ok(Receipt::new("wallet", amount)) } } }
pub fn display_name(&self) -> &str { match self { PaymentMethod::CreditCard { .. } => "Credit Card", PaymentMethod::BankTransfer { .. } => "Bank Transfer", PaymentMethod::DigitalWallet { .. } => "Digital Wallet", } }}Each method implementation handles all variants in one place. This centralization has advantages when the logic for different variants is similar or interrelated. Adding a method requires no changes to existing code beyond implementing the new match arms.
The trade-off is that adding a new variant requires modifying all match expressions. The compiler flags incomplete matches, ensuring updates are not forgotten, but the modifications spread across the codebase. This is the expression problem: row extensibility (adding variants) and column extensibility (adding operations) trade off against each other.
Enums suit scenarios where variants are known at design time and change rarely. Payment methods, document types, message formats, state machine states, and similar bounded sets map naturally to enums. When new variants arise frequently or are defined outside the crate, traits offer better extensibility.
The following diagram illustrates when to prefer enums versus traits:
graph TD
A["Need polymorphism?"] --> B["Is the set of types known and closed?"]
B -- Yes --> C["Are new operations added frequently?"]
B -- No --> T["Use trait"]
C -- Yes --> E["Use enum"]
C -- No --> T
T --> H["Need heterogeneous collections?"] --> D["Use dyn Trait"]
[!visual-conversion] Decision flow for choosing between enums and traits. Print flowchart (PDF 310, printed p. 304) recreated in Mermaid; labels and Yes/No edges verbatim.
The Visitor pattern in Rust
The Visitor pattern from object-oriented programming adds operations to a type hierarchy without modifying the types. In Rust, enums combined with a trait-based visitor achieve the same goal with compile-time safety.
The following example implements visitors for a document model:
// Document elements (the "element" hierarchy)enum Element { Paragraph(String), Heading { level: u8, text: String }, List(Vec<String>), Code { language: String, content: String },}
// Visitor trait (operations that can be performed on elements)trait Visitor { fn visit_paragraph(&mut self, text: &str); fn visit_heading(&mut self, level: u8, text: &str); fn visit_list(&mut self, items: &[String]); fn visit_code(&mut self, language: &str, content: &str);}
impl Element { fn accept(&self, visitor: &mut dyn Visitor) { match self { Element::Paragraph(text) => visitor.visit_paragraph(text), Element::Heading { level, text } => visitor.visit_heading(*level, text), Element::List(items) => visitor.visit_list(items), Element::Code { language, content } => visitor.visit_code(language, content), } }}
// HTML renderer visitorstruct HtmlRenderer { output: String,}
impl HtmlRenderer { fn new() -> Self { HtmlRenderer { output: String::new() } }}
impl Visitor for HtmlRenderer { fn visit_paragraph(&mut self, text: &str) { self.output.push_str(&format!("<p>{}</p>\n", text)); }
fn visit_heading(&mut self, level: u8, text: &str) { self.output.push_str(&format!("<h{}>{}</h{}>\n", level, text, level)); }
fn visit_list(&mut self, items: &[String]) { self.output.push_str("<ul>\n"); for item in items { self.output.push_str(&format!("<li>{}</li>\n", item)); } self.output.push_str("</ul>\n"); }
fn visit_code(&mut self, language: &str, content: &str) { self.output.push_str(&format!( "<pre><code class=\"language-{}\">{}</code></pre>\n", language, content )); }}
// Word counter visitorstruct WordCounter { count: usize,}
impl WordCounter { fn new() -> Self { WordCounter { count: 0 } }}
impl Visitor for WordCounter { fn visit_paragraph(&mut self, text: &str) { self.count += text.split_whitespace().count(); }
fn visit_heading(&mut self, _level: u8, text: &str) { self.count += text.split_whitespace().count(); }
fn visit_list(&mut self, items: &[String]) { for item in items { self.count += item.split_whitespace().count(); } }
fn visit_code(&mut self, _language: &str, _content: &str) { // Don't count code as words }}
fn main() { let document = vec![ Element::Heading { level: 1, text: "Welcome".to_string() }, Element::Paragraph("This is a sample document.".to_string()), Element::List(vec!["First item".to_string(), "Second item".to_string()]), Element::Code { language: "rust".to_string(), content: "fn main() {}".to_string() }, ];
// Render to HTML let mut renderer = HtmlRenderer::new(); for element in &document { element.accept(&mut renderer); } println!("HTML:\n{}", renderer.output);
// Count words let mut counter = WordCounter::new(); for element in &document { element.accept(&mut counter); }
println!("Word count: {}", counter.count);}This design separates data (the Element enum) from operations (the Visitor trait). Adding new visitors requires no modification to Element. Adding new element variants requires updating existing visitors, but the compiler ensures completeness through match exhaustiveness checking.
The newtype pattern for behavior extension
Sometimes the goal is not hierarchy but variation: the same underlying type with different behavior in different contexts. The newtype pattern wraps an existing type in a single-field struct, creating a distinct type that can have its own trait implementations.
Consider a string that represents an email address. Using String directly provides no type safety; any string can be passed where an email is expected. A newtype creates a distinct type:
pub struct EmailAddress(String);
impl EmailAddress { pub fn new(s: &str) -> Result<Self, ValidationError> { if s.contains('@') && s.contains('.') { Ok(EmailAddress(s.to_string())) } else { Err(ValidationError::InvalidEmail) } } pub fn as_str(&self) -> &str { &self.0 }}The newtype has zero runtime overhead (the wrapper compiles away) but provides compile-time distinction. Functions taking EmailAddress cannot accidentally receive arbitrary strings. The newtype can implement traits differently than the underlying type or implement traits the underlying type does not support.
This pattern appears frequently in Rust codebases. Newtypes distinguish user IDs from product IDs, distances from durations, validated from unvalidated data. Each newtype carries semantic meaning that the type system enforces, catching errors at compile time that would be runtime bugs with raw primitive types.
Decision guide: choosing the right approach
Translating inheritance hierarchies to Rust requires choosing among composition, traits, enums, and newtypes. The choice depends on what the inheritance achieved and what flexibility the design requires.
When inheritance primarily shared data and implementation, composition is the natural fit. Extract the shared parts into a separate struct. Embed that struct in types that need its capabilities. Implement methods that delegate to the embedded component or access its data directly.
When inheritance primarily defined interfaces that multiple implementations fulfill, traits capture the same contract. Define traits for the capabilities required. Implement those traits for each concrete type. Use trait bounds in generic functions to express requirements, or trait objects for heterogeneous collections.
When inheritance modeled a fixed set of related variants with shared operations, enums often provide cleaner code. Define an enum with a variant for each case. Implement methods using pattern matching. Accept the trade-off that adding variants requires touching existing code.
When inheritance created type distinctions without significant behavior differences, newtypes provide type safety without complexity. Wrap the underlying type in a tuple struct. Implement conversions and trait implementations as needed.
The following algorithm summarizes this decision process:
PROCEDURE ChooseRustApproach(OOPHierarchy)BEGIN Analyze the inheritance hierarchy to identify its primary purpose
IF hierarchy shares data fields and method implementations THEN Extract shared fields into a separate struct Embed that struct as a field in each type Delegate method calls to the embedded component RESULT: Composition
ELSE IF hierarchy defines interfaces with multiple implementations THEN IF the set of implementing types is open (extensible) THEN Define traits for each capability Implement traits on each concrete type IF collections must hold mixed types THEN Use dyn Trait for runtime polymorphism ELSE Use generics with trait bounds END IF RESULT: Traits ELSE Proceed to enum evaluation END IF
ELSE IF hierarchy models a fixed, closed set of variants THEN IF new operations are added more often than new variants THEN Define enum with one variant per type Implement methods using match expressions RESULT: Enum ELSE Consider traits for variant extensibility END IF
ELSE IF hierarchy creates type distinctions without behavior changes THEN Wrap the base type in a tuple struct Implement specific traits as needed RESULT: Newtype
ELSE Combine approaches as appropriate END IFENDThe following diagram visualizes this decision flow:
graph TD
A["Analyze OOP Hierarchy"] --> P{"Primary purpose?"}
P --> DI["Defines interfaces"]
P --> MV["Models fixed variants"]
P --> SD["Shares data & implementation"]
P --> CT["Creates type distinctions"]
DI --> EX{"Set of types extensible?"}
EX -- Yes --> MX{"Need mixed-type collections?"}
EX -- No --> NO{"New operations more frequent?"}
MV --> NO
SD --> UC["Use Composition"]
CT --> UN["Use Newtype"]
MX -- Yes --> DT["Use dyn Trait"]
MX -- No --> TG["Use Traits with Generics"]
NO -- No --> TG
NO -- Yes --> UE["Use Enum"]
[!visual-conversion] Decision flowchart for translating OOP inheritance to Rust patterns. Print flowchart (PDF 317, printed p. 311) recreated in Mermaid. The print artwork is small and low-contrast; labels were read from a 3× crop and each agrees with the pseudocode above.
These approaches combine. A document editor might use enums for block types (paragraph, heading, list), traits for rendering capabilities (Drawable, Serializable), composition for shared properties (style, position), and newtypes for validated content (SafeHtml, ValidatedUrl). The combination addresses each concern with the appropriate mechanism rather than forcing everything through inheritance.
The absence of inheritance in Rust is not a limitation to work around but a design decision that encourages cleaner architecture. Code that would have used inheritance splits into smaller, more focused pieces. The relationships between types become explicit rather than implicit. Changes to one type do not silently affect others through inherited dependencies. The resulting designs tend toward flexibility and maintainability.
The Takeaway
Rust omits inheritance deliberately, avoiding the fragile base class problem, deep hierarchies, and the diamond problem. The mechanisms that replace inheritance each address specific concerns that inheritance bundled together.
Composition embeds components as fields, delegating behavior to those components. This provides code reuse without coupling, allows multiple independent components, and enables runtime flexibility that inheritance cannot match.
Trait hierarchies express capability contracts. Supertraits define prerequisite capabilities. Types implement traits independently, enabling precise bounds that request exactly the capabilities needed.
Enums provide closed-set polymorphism. When variants are known at design time, pattern matching handles each case with compiler-enforced exhaustiveness. The trade-off favors adding operations over adding variants.
Newtypes create distinct types from existing ones with zero runtime cost. They provide type safety and custom trait implementations for what would otherwise be primitive types.
The choice among these mechanisms depends on what the original inheritance achieved. Shared implementation suggests composition. Shared interface suggests traits. Fixed variants suggest enums. Type distinction suggests newtypes. Real designs often combine multiple approaches, using each for its strengths.
The next chapter examines creational patterns in Rust, exploring how factories, builders, and singletons translate when classes and inheritance are unavailable. The patterns themselves remain useful; their implementations adapt to Rust’s model.