Sub topic 2
Static Dispatch, Trait Objects, and Trait Design
Assume you know Rust ownership, borrowing, basic generics, and how to run a Cargo program. This chapter compares how Rust chooses trait implementations and how that choice affects trait design.
Static dispatch and monomorphization
Static dispatch means the compiler chooses the exact method implementation before the program runs. Generic code usually uses static dispatch:
trait Summary {
fn summarize(&self) -> String;
}
struct Post(String);
impl Summary for Post {
fn summarize(&self) -> String {
format!("Post: {}", self.0)
}
}
fn print_summary<T: Summary>(item: &T) {
println!("{}", item.summarize());
}
fn main() {
print_summary(&Post(String::from("Hello")));
}The compiler performs monomorphization, which means it creates specialized machine code for each concrete type used with a generic function. This often enables inlining and has no run-time vtable lookup. The trade-off is that many types can increase compile time and binary size.
Trait objects with `dyn Trait`
A trait object stores a value whose concrete type is hidden behind a trait interface. dyn Trait uses dynamic dispatch: Rust looks up the method through a run-time vtable.
fn print_all(items: &[Box<dyn Summary>]) {
for item in items {
println!("{}", item.summarize());
}
}Trait objects let one collection contain different types that implement the same trait. Use them when the concrete types vary at run time or when reducing generic code is more important than maximum dispatch performance.
Associated types versus type parameters
An associated type chooses one related type per implementation. A generic trait can support multiple implementations for different type combinations.
| Design | Meaning |
|---|---|
| `trait Add<Rhs> { type Output; }` | One implementation can vary by right-hand type |
| `trait Iterator { type Item; }` | Each implementing type has one item type |
Associated types make APIs easier to use when the relationship is unique. Use generic parameters when the same type may implement the trait repeatedly with different parameters.
Traits with generic parameters
trait Convert<T> {
fn convert(&self, value: T) -> String;
}This trait is not automatically usable as dyn Convert<_> because its method relationship depends on a generic parameter. Generic traits are useful for compile-time relationships, while object-safe traits usually expose concrete method signatures.
Building traits on other traits
A supertrait requires another trait:
use std::fmt::Display;
trait Label: Display {
fn label(&self) -> String {
self.to_string()
}
}Any Label implementer must implement Display, so label can call Display methods. This composes capabilities and documents a requirement.
Exercise
When should you prefer dyn Trait over a generic function?
Show answer
Prefer it when concrete types must be mixed or selected at run time. Prefer generics when compile-time specialization and performance matter.