Sub topic 9
Generics or trait objects?
Rust gives you two ways to write code that works with many types that share a trait. Generics (T: Trait) resolve which implementation to call at compile time. Trait objects (dyn Trait) resolve it at run time. This chapter explains how each one works, what each costs, and how to choose between them.
This chapter assumes you can write a trait and implement it for a type, you know what a trait bound is, and you know Box<T> and Vec<T>. It also builds on the monomorphization chapter, which covers how the compiler copies generic code for each concrete type.
Two ways to accept "anything that implements Shape"
Here is one trait, two types, and a function written both ways.
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 print_static<T: Shape>(s: &T) {
println!("{:.2}", s.area());
}
fn print_dynamic(s: &dyn Shape) {
println!("{:.2}", s.area());
}
fn main() {
let c = Circle(1.0);
let sq = Square(2.0);
print_static(&c);
print_static(&sq);
print_dynamic(&c);
print_dynamic(&sq);
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("{:.2}", total);
}The call sites for print_static and print_dynamic look the same. The compiled code is different.
Static dispatch: what generics do
print_static is monomorphized. The compiler generates one copy for Circle and one for Square. In each copy, s.area() is a direct call to a known function, so the compiler can inline it and optimize across the call.
The costs show up elsewhere:
- Each distinct type adds another copy of the function, which grows the binary and compile time.
- All values of a type parameter
Thave the same concrete type. AVec<T>holds circles or squares, never both. - The concrete type must be known at compile time at every call site.
Dynamic dispatch: what trait objects do
&dyn Shape is a fat pointer, which means it holds two machine words:
- A pointer to the data.
- A pointer to a vtable for the concrete type.
A vtable (virtual method table) is a static table the compiler builds for each (type, trait) pair. It holds the type's size and alignment, its destructor, and a pointer to each trait method. A call like s.area() loads the function pointer from the vtable and calls it indirectly.
use std::mem::size_of;
fn main() {
println!("{}", size_of::<&u8>());
println!("{}", size_of::<&dyn std::fmt::Debug>());
}On a 64-bit target this prints 8 and then 16.
The function exists once, no matter how many types implement the trait. That keeps code size down. The costs are:
- Each method call goes through an indirect jump, and the compiler usually cannot inline through it.
- Trait objects are unsized, so you must put them behind a pointer:
&dyn Trait,Box<dyn Trait>,Rc<dyn Trait>, orArc<dyn Trait>. - Boxed trait objects mean one heap allocation per value.
- Only methods that fit in a vtable are callable (see the next section).
The indirect call is usually a small cost, on the order of a few nanoseconds. It matters in hot inner loops and rarely anywhere else. Measure before you decide on speed grounds.
Dyn compatibility: what a trait object can use
A trait can be made into a trait object only if it is dyn compatible (older documentation calls this "object safe"). The vtable must have one fixed entry per method, so the compiler rejects methods it cannot put there. The common causes are:
- A method returns
Self, such asfn dup(&self) -> Self. The caller of adyn Traitdoes not know the concrete type. - A method has its own type parameters, such as
fn map<U>(&self, f: U). That would need infinitely many vtable entries. - A method has no
selfreceiver, such as an associated functionfn new() -> Self. - The trait requires
Self: Sized.
You do not need to give up the whole trait. Add where Self: Sized to the offending method. The method is then excluded from the vtable, and the rest of the trait stays usable as dyn.
trait Shape {
fn area(&self) -> f64;
fn boxed(self) -> Box<dyn Shape>
where
Self: Sized + 'static,
{
Box::new(self)
}
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
let shape: Box<dyn Shape> = Square(3.0).boxed();
println!("{}", shape.area());
}You can call boxed on a concrete Square. You cannot call it through a dyn Shape, because that method is not in the vtable.
Heterogeneous collections and return types
The strongest reason to choose dyn is that you need different concrete types behind one type. A Vec<T> cannot hold a Circle and a Square, but Vec<Box<dyn Shape>> can. The same applies to a plugin list, a set of event handlers, or a UI widget tree where the set of types is open.
Return types follow the same rule. impl Trait in return position hides the concrete type, but there is still exactly one. This function would not compile if the two branches returned different closure types:
fn pick(loud: bool) -> Box<dyn Fn(&str) -> String> {
if loud {
Box::new(|s| s.to_uppercase())
} else {
Box::new(|s| s.to_string())
}
}
fn main() {
println!("{}", pick(true)("hello"));
println!("{}", pick(false)("hello"));
}Every closure has its own unique type. Returning impl Fn(&str) -> String here fails with a "no two closures have the same type" error. Boxing both as dyn Fn gives them one shared type.
Making generics accept trait objects
A generic parameter has an implicit Sized bound. So fn f<T: Shape>(s: &T) rejects &dyn Shape, because dyn Shape is unsized. Write T: ?Sized to relax that bound:
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn print_area<T: Shape + ?Sized>(s: &T) {
println!("{:.1}", s.area());
}
fn main() {
let sq = Square(2.0);
print_area(&sq);
let dynamic: &dyn Shape = &sq;
print_area(dynamic);
}The same function now works for both. For the dyn Shape case, the compiler instantiates T = dyn Shape and the call inside goes through the vtable.
Common errors
- Expecting
Box<dyn Shape>to implementShape. It does not unless you write that impl.dyn ShapeimplementsShape, but aBoxaround it is a different type. Pass&*boxed, or writeimpl<T: Shape + ?Sized> Shape for Box<T>. - Forgetting the pointer.
Vec<dyn Shape>andfn f(s: dyn Shape)fail because the size is unknown. UseVec<Box<dyn Shape>>and&dyn Shape. - Hidden
'static.Box<dyn Shape>meansBox<dyn Shape + 'static>. A trait object that holds a borrow needs an explicit lifetime, such asBox<dyn Shape + 'a>. - A generic method in the trait. This makes the whole trait fail dyn compatibility. Add
where Self: Sized, or take&dynarguments instead of a type parameter. - Using
dynby default. If all the types are known at compile time, a generic is usually simpler and faster, and it avoids the allocation.
Choosing
| Question | Generics or `impl Trait` | `dyn Trait` |
|---|---|---|
| Dispatch | Compile time, inlinable | Run time, through a vtable |
| One collection of mixed types | No | Yes |
| Code size | One copy per type | One copy total |
| Heap allocation needed | No | Usually, for `Box` |
| Open set of types at run time | No | Yes |
| Trait restrictions | Any trait | Dyn compatible only |
| Return different types from branches | No | Yes |
As a rule of thumb:
- Start with generics or
impl Trait. They are the default and cost nothing at run time. - Switch to
dyn Traitwhen you need a mixed collection, a runtime-chosen implementation, or different types returned from one function. - Also consider
dynwhen monomorphization bloats the binary or compile time. This is more common in large libraries than in applications. - If you have a closed, small set of types, consider an
enum. It stores the values inline and needs no vtable.
Exercise
A function must return either a Circle or a Square depending on a runtime flag, and the caller only calls .area() on the result. Why does fn make(flag: bool) -> impl Shape fail, and what is a fix?
Show answer
impl Shape in return position stands for exactly one concrete type, chosen by the function body. The two branches return different types (Circle and Square), so the compiler cannot pick one. Return Box<dyn Shape> and box each value: if flag { Box::new(Circle(1.0)) } else { Box::new(Square(1.0)) }. An enum with Circle and Square variants that implements Shape also works.
Exercise
You write fn total<T: Shape>(items: &[Box<T>]). Why can you not pass it a Vec<Box<dyn Shape>>, and how do you change the signature so you can?
Show answer
The implicit Sized bound on T rejects T = dyn Shape, because dyn Shape is unsized. Write T: Shape + ?Sized. The call then compiles with T = dyn Shape, and calls inside go through the vtable.