Sub topic 8
Generics, impl Trait, or dyn Trait?
This chapter assumes you know how to define traits, write generic functions with trait bounds, and use Box and references. It helps you choose among three ways to write code that works with many types.
The three forms
All three forms below accept "something that implements Shape". They differ in when the compiler decides which method to call.
| Form | Dispatch | Copies of code | Mixed types in one collection |
|---|---|---|---|
| `fn f<T: Shape>(x: &T)` | Static | One per concrete type | No |
| `fn f(x: &impl Shape)` | Static | One per concrete type | No |
| `fn f(x: &dyn Shape)` | Dynamic (vtable) | One | Yes, behind a pointer |
impl Trait in argument position is shorthand for a generic parameter. The one difference is that you can't name the type with turbofish syntax (f::<Square>(...)) when you use impl Trait in arguments.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
// Static dispatch: the compiler generates a copy of this function for each concrete type.
fn print_static(s: &impl Shape) {
println!("{}", s.area());
}
// Dynamic dispatch: one compiled function, with the method looked up through a vtable.
fn print_dyn(s: &dyn Shape) {
println!("{}", s.area());
}
fn main() {
let sq = Square(3.0);
print_static(&sq);
print_dyn(&sq);
}Both calls print 9.
Decision criteria
Start from what your program needs, not from speed.
- Use generics or
impl Traitwhen each call site knows one concrete type. The compiler can inline the method and optimize across the call. The cost is more compiled code, because each type gets its own copy. - Use
dyn Traitwhen the concrete type is only known at runtime, or when one collection must hold different types. Examples are plugins, a list of UI widgets, or a handler chosen from a config file. The cost is an indirect call through the vtable, which usually blocks inlining, and a pointer to the value (often a heap allocation withBox). - Use
impl Traitin return position when a function returns one concrete type that you want to hide. Every path through the function must return the same type.
fn make_square() -> impl Shape {
Square(2.0)
}If a function must return different types depending on a runtime value, impl Trait fails to compile. Return Box<dyn Shape> instead.
fn make(big: bool) -> Box<dyn Shape> {
if big {
Box::new(Square(10.0))
} else {
Box::new(Square(1.0))
}
}Common mistakes
- Reaching for
dynby habit. If you only ever pass one type, generics are simpler and faster. You can move todynlater if you need it. - Expecting speed from
dynto matter. For most code, a vtable call costs little compared with the work inside the method. Measure before you rule it out. - Code size from generics. A generic function used with many types is compiled once for each type. In a large library this can grow the binary and slow compilation. A common remedy is a thin generic wrapper that calls a non-generic inner function.
- Mixing types in a
Vec<T>. AVec<T>holds one type. UseVec<Box<dyn Shape>>for mixed values.
Exercise
A function reads a setting at runtime and returns either a Circle or a Rect, both of which implement Shape. Why does fn pick(c: bool) -> impl Shape fail, and what return type fixes it?
Show answer
impl Trait in return position stands for exactly one concrete type, and the two branches return different types. Return Box<dyn Shape> and wrap each value with Box::new, so both branches have the same type and the method is called through the vtable.