Sub topic 8
Generics, impl Trait, or dyn Trait?
You can often write the same function with a generic parameter, with impl Trait, or with dyn Trait. This chapter gives you criteria for choosing between them. It assumes you can define and implement traits, write trait bounds, and use Box and references. It also assumes you know that dyn Trait is unsized and used behind a pointer, and that a method call on it goes through a vtable.
Three spellings of one call
The same behavior can be requested in three ways:
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.0 * self.0
}
}
// 1. Named generic parameter.
fn show_generic<T: Shape>(s: &T) {
println!("{:.2}", s.area());
}
// 2. Argument-position impl Trait (shorthand for an anonymous generic).
fn show_impl(s: &impl Shape) {
println!("{:.2}", s.area());
}
// 3. Trait object.
fn show_dyn(s: &dyn Shape) {
println!("{:.2}", s.area());
}
fn main() {
let sq = Square(2.0);
let c = Circle(1.0);
show_generic(&sq);
show_impl(&c);
show_dyn(&sq);
show_dyn(&c);
}The first two are static dispatch. The compiler generates one copy of the function per concrete type (monomorphization) and resolves each call at compile time. The third compiles once and looks the method up in a vtable at runtime.
Forms 1 and 2 are nearly identical. The one practical difference is that a named parameter T can appear more than once in a signature, as in fn same<T: Shape>(a: &T, b: &T), which forces both arguments to be the same type. Two impl Shape arguments may be different types. Callers can also write show_generic::<Square>(&sq) with an explicit type, but cannot do that with impl Trait in argument position.
What each choice costs
| Property | Generic or `impl Trait` argument | `dyn Trait` |
|---|---|---|
| Method resolution | Compile time | Runtime, through a vtable |
| Inlining | Possible, and often applied | Usually blocked at the call through the pointer |
| Compiled code | One copy per concrete type | One copy |
| Pointer size | Thin, or no pointer at all | Fat: data pointer plus vtable pointer |
| Mixed concrete types in one collection | Not possible | Possible |
| Needs a pointer or allocation | No | Yes (`&`, `Box`, `Rc`, `Arc`) |
| Trait must be dyn compatible | No | Yes |
Two points in this table are often overstated.
- Speed. A vtable call costs an indirect jump. The larger cost is that the optimizer cannot inline across it, so a hot inner loop calling a tiny method can be much slower. A call that does real work (I/O, parsing, a lock) makes the difference negligible. Measure before choosing on speed alone.
- Code size. Monomorphization duplicates code for every type used. A large generic function instantiated with many types grows the binary and the compile time. A common mitigation is a thin generic wrapper that converts its argument and calls a non-generic inner function.
When the choice is forced
Some designs leave only one option.
You need mixed types in one collection: use dyn. Vec<T> holds a single T. A Vec<Box<dyn Shape>> can hold squares and circles together. A &[&dyn Shape] does the same without allocating.
You need to pick a type at runtime: use Box<dyn Trait>. impl Trait in return position names one hidden concrete type, chosen by the function body. Two branches that return different types do not compile with impl Trait.
fn evens(limit: u32) -> impl Iterator<Item = u32> {
(0..limit).filter(|n| n % 2 == 0)
}
fn pick(rev: bool, limit: u32) -> Box<dyn Iterator<Item = u32>> {
if rev {
Box::new((0..limit).rev())
} else {
Box::new(0..limit)
}
}
fn main() {
let a: Vec<u32> = evens(7).collect();
let b: Vec<u32> = pick(true, 3).collect();
println!("{:?} {:?}", a, b);
}This prints [0, 2, 4, 6] [2, 1, 0]. evens returns one unnameable type (a Filter over a Range with a closure), so impl Iterator hides it at no cost. pick returns a Rev<Range> in one branch and a Range in the other, so it needs Box<dyn Iterator>. Closures behave the same way: each has a unique type, so returning one of several closures needs Box<dyn Fn>.
The trait is not dyn compatible: use generics. A trait with a generic method, or one that returns Self, cannot be made into dyn Trait unless those methods are opted out with where Self: Sized. If a method must stay callable on the trait object, the design has to change. If it doesn't need to be, generics work without any change.
You want a type you can't name in a struct field: use a generic parameter or Box<dyn>. Returning impl Trait is fine for functions, but a field needs a nameable type. That leaves the next decision.
Struct fields: a type parameter or a boxed object
use std::io::Write;
struct Generic<W: Write> {
out: W,
}
struct Dynamic {
out: Box<dyn Write>,
}
impl<W: Write> Generic<W> {
fn log(&mut self, m: &str) {
writeln!(self.out, "{m}").unwrap();
}
}
impl Dynamic {
fn log(&mut self, m: &str) {
writeln!(self.out, "{m}").unwrap();
}
}
fn main() {
let mut a = Generic { out: Vec::<u8>::new() };
a.log("hi");
let mut b = Dynamic { out: Box::new(std::io::stdout()) };
b.log("hello");
println!("{}", a.out.len());
}This prints hello and then 3 (the bytes hi and a newline).
Generic<Vec<u8>> and Generic<Stdout> are different types. You cannot put them in the same Vec, store them in one field, or return either from the same function without more machinery. The type parameter also spreads. Every struct that contains a Generic<W> needs its own W, and so does every function that takes it, unless it picks a concrete type.
Dynamic has one type no matter what writer it holds. It costs a heap allocation and an indirect call per write, and it hides the concrete type, so you can't read a.out.len() as the example does with the generic version.
A reasonable default for library types is generic when the type is a building block in a hot path, and Box<dyn Trait> when it is a long-lived component that holds a runtime-chosen strategy, such as a logger sink, a plugin, or a callback.
A decision path
Common errors
- Different types in
impl Traitreturns. ReturningSquarein one branch andCirclein another fails with a mismatched types error (E0308), even though both implementShape. Box them asBox<dyn Shape>. dyn Traitused by value.fn f(s: dyn Shape)fails because the size is unknown. Use&dyn ShapeorBox<dyn Shape>.- Adding a generic method to a trait you use as
dyn. The trait stops being dyn compatible, and everydyn Traituse errors. Addwhere Self: Sizedto that method, or move it to an extension trait. - Reaching for
dyntoo early. If every call site uses one known type, generics give you inlining and simpler types with no cost to callers. - Reaching for generics too early. If the generic parameter leaks into five structs and three traits just to avoid one
Box, a trait object would be simpler.
Exercise
A function fn make(kind: &str) -> ??? returns a Square when kind == "sq" and a Circle otherwise, both implementing Shape. Which return type works, and why does impl Shape not?
Show answer
Box<dyn Shape> works. impl Shape in return position stands for exactly one concrete type chosen by the function body, so returning Square in one branch and Circle in the other is a type mismatch. A boxed trait object has a single type regardless of what it holds, and the method calls are resolved at runtime through its vtable.
Exercise
You write struct Cache<S: Store> { store: S } and later need a Vec holding caches backed by different store types. What are two ways to fix this, and what does each cost?
Show answer
Change the field to Box<dyn Store> (the trait must be dyn compatible), which gives Cache a single type at the cost of one allocation per store and indirect calls. Alternatively, keep the generic and wrap each cache in a trait object of its own, such as Box<dyn CacheOps>, which keeps static dispatch inside each cache but adds a boxed layer at the collection level.