1. Why Class Inheritance Keeps Getting Tangled
Traditional object-oriented (OOP) languages like Java and C++ organize code around classes and inheritance.
A class is a blueprint that bundles data (fields) and behavior (methods) together, and inheritance lets a child class copy everything from a parent blueprint.
Like a family tree or a biological taxonomy, it stacks types into a strict vertical hierarchy.
Rust has no class keyword at all. There is also no syntax for one struct to inherit from (extends) another struct.
As we saw in Part 1, Rust skips class inheritance and borrows the idea of typeclasses from Haskell, giving us a tool called traits.
A classic example shows why inheritance gets tangled so easily. Suppose you create an Animal class and inherit a Bird class from it with a fly() method.
When you add Sparrow and Eagle, this family tree looks clean and logical.
The trouble starts the moment you add Penguin. A penguin is definitely a Bird, yet it cannot fly.
Because it already inherited fly() from Bird, you are forced to either throw an error inside Penguin's fly() method or tear apart the whole tree into "FlyingBird" and "FlightlessBird."
Class inheritance tends to break down for three reasons in practice. First comes the Fragile Base Class problem. Because data and behavior are locked together in a vertical tree, a small change to a parent class can unexpectedly break child classes hanging underneath it.
The second is the Diamond Problem. Imagine classes B and C both inherit from parent A and each overrides the same method in a different way. When a child class D inherits from both B and C and calls that method, it becomes ambiguous which parent's version should run (the hierarchy forms a diamond shape, hence the name).
The third snag is adding behavior to a class from a library. If the class allows subclassing, add the new method to a subclass; it will be available on instances of that subclass. A wrapper is useful when the library has already handed you an instance of the original class: it holds that object and provides the extra method.
2. Traits: Contracts That Separate Data from Capability
Rust's answer is refreshingly direct. It separates "what a type holds (data)" from "what a type can do (capability)." Pure data lives in a struct or an enum, while shared behavioral promises live in a separate contract called a trait.1
Think of a trait like a real-world license or certification. A driver's license or a lifeguard certificate does not care who your parents are; anyone who passes the required test earns the qualification.
In Rust, you use the impl Trait for Type syntax to grant only the certifications a type actually needs.
As shown in the diagram above, implementing only Swim for Penguin and only Fly for Sparrow removes the forced inheritance tree completely. What if you later need a Duck that can both swim and fly?
You do not refactor any hierarchy; you simply implement both Swim and Fly side by side.
Handling different types through one shared contract is called polymorphism. Another major perk of traits is extending external types.
As long as you define the trait yourself, you can use impl to attach new capabilities directly to existing standard library types like f32 or String.
3. Designing L-System Rules with a Trait
We just used a line from the terminal to change an order. This time a string will give us something to draw. We'll see how that string grows before we use it to make a picture.
A Lindenmayer system, or L-System, starts with a string and a set of rules for replacing individual characters. Start with F and replace it with F[+F]F[-F]F: that's the first result. On the next pass, replace the Fs that are already in that result. Any characters created on that pass wait until the following one.
The Fractal Tree and Koch Curve presets both start at F and produce different strings. The function that applies the rules only needs a name, a starting string (the axiom), and a method that answers what to substitute for a character. RuleSet defines those methods, and each preset supplies its own rules. This example prints the first result as a string; Part 9 reads the symbols and turns them into lines.
trait RuleSet {
fn name(&self) -> &str;
fn axiom(&self) -> &str;
fn rewrite(&self, ch: char) -> Option<&str>;
}
struct FractalTree;
impl RuleSet for FractalTree {
fn name(&self) -> &str {
"Fractal Tree"
}
fn axiom(&self) -> &str {
"F"
}
fn rewrite(&self, ch: char) -> Option<&str> {
match ch {
'F' => Some("F[+F]F[-F]F"),
_ => None,
}
}
}
struct KochCurve;
impl RuleSet for KochCurve {
fn name(&self) -> &str {
"Koch Curve"
}
fn axiom(&self) -> &str {
"F"
}
fn rewrite(&self, ch: char) -> Option<&str> {
match ch {
'F' => Some("F+F-F-F+F"),
_ => None,
}
}
}
// Static dispatch: generates specialized code per type at compile time
fn preview_once(rule: &impl RuleSet) {
let mut next = String::new();
for ch in rule.axiom().chars() {
match rule.rewrite(ch) {
Some(replaced) => next.push_str(replaced),
None => next.push(ch),
}
}
println!("[{}] 1 step -> {}", rule.name(), next);
}
fn main() {
let tree = FractalTree;
let koch = KochCurve;
preview_once(&tree);
preview_once(&koch);
// Dynamic dispatch: group different types as RuleSet and call methods
let presets: Vec<&dyn RuleSet> = vec![&tree, &koch];
println!("Registered presets: {}", presets.len());
for rule in presets {
println!("Preset: {}", rule.name());
}
}Output:
[Fractal Tree] 1 step -> F[+F]F[-F]F
[Koch Curve] 1 step -> F+F-F-F+F
Registered presets: 2
Preset: Fractal Tree
Preset: Koch CurveThere are several new pieces of syntax here, so let's walk through them from top to bottom.
The trait RuleSet block is our capability contract: it lists each method's name, parameters, and return type, ending with a semicolon (;) instead of a body.
Here, &self means the method borrows the receiver read-only, and -> &str means it returns a string slice.
Notice the return type of rewrite(&self, ch: char) -> Option<&str> as well. Characters with a replacement rule like 'F' return Some("F[+F]F[-F]F"), while characters with no rule like '+' or '-' return None.
As in Part 7, Option gives us a way to return None when there's no rule. preview_once then copies the original character into the next string.
Next come struct FractalTree; and struct KochCurve;, which are unit structs with zero fields. Because these rules are fixed in code and need no stored fields, we declare empty named types without curly braces.
They take up 0 bytes of memory at runtime, yet they are full-fledged distinct types that can implement traits.
The block impl RuleSet for FractalTree { ... } states how FractalTree fulfills the RuleSet contract. If you forget any of name, axiom, or rewrite, or get a return type wrong, the compiler immediately stops with an error.
Even if you mistype a method name as a beginner, Rust catches it before the program ever runs.
Now trace through preview_once. It loops over each character of rule.axiom().chars() and passes it to rule.rewrite(ch), appending the replacement on Some(replaced) (push_str) or keeping the original character on None (push).
That single preview_once function can expand both FractalTree and KochCurve.
4. Choosing Between impl Trait (Static) and dyn Trait (Dynamic)
In the second half of the code, RuleSet appears in two different forms: &impl RuleSet and &dyn RuleSet.
Dispatch selects the type's actual implementation when you call a method. The parameter &impl RuleSet in preview_once uses static dispatch. It means "accept a reference to any type that implements RuleSet," without checking the type at runtime.
Instead, the compiler inspects main and generates two specialized copies of preview_once at compile time: one for FractalTree and one for KochCurve. Turning one generic function into concrete, type-specific versions is called monomorphization. Because the exact function address is baked in ahead of time, there is zero runtime lookup cost through a virtual method table (vtable). You get clean abstraction at the exact same speed as hand-written functions.
Then why do we ever need &dyn RuleSet instead of using static dispatch everywhere? A Rust Vec requires every element to have the exact same type. Since FractalTree and KochCurve are different types, writing vec![tree, koch] directly will be rejected by the compiler.
Yet if you want to show a list of presets in a GUI menu, or swap rules at runtime based on user input, you need to hold different types in one collection. That is where dynamic dispatch and the trait object &dyn RuleSet come in. Here, dyn is short for "dynamic."2
Under the hood, a single &dyn RuleSet reference carries a pair of pointers. One points to the actual data (&tree or &koch), and the other points to that type's virtual method table (vtable), a small directory listing where its methods live. Follow the final loop in main: for rule in presets { println!("Preset: {}", rule.name()); }. On the first iteration, rule points to &tree, checks FractalTree's vtable for name, and prints "Fractal Tree." On the second iteration, it checks &koch's vtable and prints "Koch Curve," all from one identical call site.
The rule of thumb is simple.
Default to static dispatch (impl Trait) when types are known at compile time and speed matters, and reach for dynamic dispatch (dyn Trait) only when you must mix different types in one collection or swap implementations at runtime.
Rust refuses to hide runtime cost, making your choice explicit with impl and dyn.
When we open a GUI window in Part 10, we will implement the eframe::App trait from the eframe crate on our own app struct (impl eframe::App for LSystemApp).
You will soon see firsthand that the entire Rust ecosystem is assembled from trait contracts rather than class inheritance.
Footnotes
- The Rust Programming Language, Ch. 10.2 Traits: Defining Shared Behavior: https://doc.rust-lang.org/book/ch10-02-traits.html β©
- The Rust Reference, Trait objects (dyn Trait): https://doc.rust-lang.org/reference/types/trait-object.html β©