Sub topic 9
Generics or trait objects?
This chapter assumes you can write a generic function with trait bounds, implement a trait for a type, and use Box and Vec. Rust gives you two ways to write code against a trait: generics (T: Trait) and trait objects (dyn Trait). Both accept many types. They differ in when the compiler picks the concrete method to call.
Static and dynamic dispatch
With a generic function, the compiler generates a separate copy for each concrete type (monomorphization). Each call goes straight to a known function, so the compiler can inline it. This is static dispatch.
With a trait object, the compiler generates one function. A &dyn Trait or Box<dyn Trait> is a fat pointer. It holds a pointer to the data and a pointer to a vtable, which is a table of the type's trait methods. Each method call looks up the function in the vtable at run time. This is dynamic dispatch.
use std::fmt::Display;
fn print_static<T: Display>(item: &T) {
println!("{item}");
}
fn print_dynamic(item: &dyn Display) {
println!("{item}");
}
fn main() {
print_static(&42);
print_static(&"hello");
print_dynamic(&42);
print_dynamic(&"hello");
}print_static is compiled twice, once for i32 and once for &str. print_dynamic is compiled once.
When you need a trait object
A generic Vec<T> holds one concrete type. If the elements have different types that share a trait, you need dyn.
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Square(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
3.14159 * self.0 * self.0
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];
println!("{}", total_area(&shapes));
}Box is needed because Circle and Square have different sizes. The Vec needs elements of one known size, and every Box is one pointer wide (a fat pointer, to be exact).
Trade-offs
| Row | Generics (`T: Trait`) | Trait objects (`dyn Trait`) |
|---|---|---|
| Dispatch | Static, resolved at compile time | Dynamic, through a vtable |
| Inlining | Possible | Not across the call |
| Binary size | Grows with each type used | One copy of the code |
| Mixed types in one collection | No | Yes |
| Allocation | None required | Usually a `Box` or reference |
| Compile time | Slower with many instantiations | Faster |
The vtable lookup costs little per call. The larger loss is that the optimizer can't inline across the call, which matters in hot loops.
Dyn compatibility
Not every trait can become a trait object. A trait is dyn compatible only if the compiler can build a vtable for it. These common features break that:
- A method that returns
Self, such asClone::clone. - A method with its own type parameters.
- Associated functions without a
selfreceiver, unless they havewhere Self: Sized.
If you write Box<dyn Clone>, the compiler rejects it. Adding where Self: Sized to a method excludes that method from the vtable. The trait stays usable as dyn, and the method is just not callable through the object.
Choosing
Exercise
A function must return either a Circle or a Square depending on a runtime flag, and both implement Shape. Why does fn make(flag: bool) -> impl Shape fail, and what return type fixes it?
Show answer
impl Shape in return position stands for one hidden concrete type, chosen at compile time. Returning Circle in one branch and Square in another gives two different types, so it fails. Return Box<dyn Shape> instead, with Box::new(Circle(1.0)) and Box::new(Square(2.0)) in the branches.