There are two ways to write a function that takes any type implementing a trait. Take a generic T: Shape (or impl Shape), and the compiler produces a copy of the function for each type it is called with. Take &dyn Shape, and there is only one function, which reads the implementation’s address from a vtable at run time. As I see it, the choice comes down to whether different types have to be mixed in one place, and whether the cost of extra copies or the cost of indirect calls is the one that matters.
I wanted to see the difference in compiler output rather than take it from the docs. So I looked at generic function symbols with nm, and at dyn calls and vtables in the assembly rustc emits. Every example below was compiled with rustc 1.94.1, edition 2021; symbols and assembly come from aarch64-apple-darwin (Apple Silicon macOS).
Defining a trait, with a default method
A trait is a set of method signatures a type has to implement. A method written with a body becomes a default method, and an implementing type uses that body unless it defines its own.
trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("area {:.1}", self.area())
}
}
struct Circle {
radius: f64,
}
struct Rect {
width: f64,
height: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.radius * self.radius
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.width * self.height
}
fn describe(&self) -> String {
format!("{}x{} rect", self.width, self.height)
}
}
fn main() {
let circle = Circle { radius: 1.0 };
let rect = Rect { width: 2.0, height: 3.0 };
println!("{}", circle.describe());
println!("{}", rect.describe());
}
area 3.1
2x3 rect
Circle implements only area, so it gets the default describe; Rect defines its own. The rest of the examples reuse these Shape, Circle, and Rect definitions.
Trait bounds and where clauses
To call a method on a type parameter T inside a generic function, the signature has to state that T implements a trait providing that method. That statement is a trait bound. Calling area without one does not compile.
trait Shape {
fn area(&self) -> f64;
}
fn total_area<T>(shapes: &[T]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {}
error[E0599]: no method named `area` found for reference `&T` in the current scope
--> bound_err.rs:6:29
|
6 | shapes.iter().map(|s| s.area()).sum()
| ^^^^ method not found in `&T`
|
= help: items from traits can only be used if the type parameter is bounded by the trait
help: the following trait defines an item `area`, perhaps you need to restrict type parameter `T` with it:
|
5 | fn total_area<T: Shape>(shapes: &[T]) -> f64 {
| +++++++
Inside the body, the bounds are all the compiler knows about T. It checks the body without knowing which type will fill T, so a method that no bound provides cannot be called. Adding T: Shape as suggested makes it compile.
With several bounds the angle brackets get long. They can move to a where clause after the signature. In this example the meaning is the same as writing them inside the brackets.
use std::fmt::Debug;
// Shape is the same as above
#[derive(Debug)]
struct Circle {
radius: f64,
}
// impl Shape for Circle is the same as above
fn print_largest<T>(shapes: &[T])
where
T: Shape + Debug,
{
if let Some(largest) = shapes.iter().max_by(|a, b| a.area().total_cmp(&b.area())) {
println!("{largest:?}");
}
}
fn main() {
let circles = [Circle { radius: 1.0 }, Circle { radius: 3.0 }];
print_largest(&circles);
}
Circle { radius: 3.0 }
Monomorphization: one copy per type
A generic function does not survive compilation as a single function. For each concrete type it is called with, the compiler makes a copy with T replaced by that type. This is monomorphization. The top half of the diagram is the generic case; the bottom half is the dyn case covered in the next section.
I compiled a program that calls print_area once with Circle and once with Rect, then checked its symbols. #[inline(never)] keeps the optimizer (-O) from inlining the function into its caller and erasing it.
// Shape, Circle, Rect are the same as above
#[inline(never)]
fn print_area<T: Shape>(shape: &T) {
println!("{:.1}", shape.area());
}
fn main() {
print_area(&Circle { radius: 1.0 });
print_area(&Rect { width: 2.0, height: 3.0 });
}
$ rustc --edition 2021 -O -C symbol-mangling-version=v0 mono.rs
$ nm -C mono | grep print_area
0000000100001ac0 t mono::print_area::<mono::Rect>
0000000100001b00 t mono::print_area::<mono::Circle>
The one print_area in the source became two functions in the binary, print_area::<Rect> and print_area::<Circle>. -C symbol-mangling-version=v0 selects v0 mangling, which keeps generic arguments in symbol names. With the default mangling, the two symbols show up as mono::print_area::h…, differing only in the hash.
Inside each copy, which implementation shape.area() calls is settled at compile time. The Rust Book calls this static dispatch. Every additional concrete type means the same body compiled again and stored again in the binary.
dyn Trait and the vtable
I changed the same function to take &dyn Shape and looked at the symbols again.
// Shape, Circle, Rect are the same as above
#[inline(never)]
fn print_area(shape: &dyn Shape) {
println!("{:.1}", shape.area());
}
fn main() {
print_area(&Circle { radius: 1.0 });
print_area(&Rect { width: 2.0, height: 3.0 });
println!("&Circle = {} bytes", std::mem::size_of::<&Circle>());
println!("&dyn Shape = {} bytes", std::mem::size_of::<&dyn Shape>());
}
3.1
6.0
&Circle = 8 bytes
&dyn Shape = 16 bytes
$ nm -C dyn_mono | grep area
0000000100001a74 t dyn_mono::print_area
0000000100001b3c t <dyn_mono::Circle as dyn_mono::Shape>::area
0000000100001b60 t <dyn_mono::Rect as dyn_mono::Shape>::area
Now there is a single print_area. In exchange, &dyn Shape is 16 bytes, twice the size of &Circle.
A &dyn Shape is a fat pointer made of two pointers. One points to the value (Circle); the other points to that type’s vtable. The Rust Reference describes the vtable as a table holding one function pointer for each trait method the concrete type implements. Just as the &str from the references and borrowing post holds a pointer and a length, the second field here holds a vtable address instead of a length.
rustc emits the vtable’s contents as a constant. I compiled, as a library, a function that returns a static as &dyn Shape, and read the assembly.
pub trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("area {:.1}", self.area())
}
}
pub struct Circle {
pub radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.radius * self.radius
}
}
pub static UNIT: Circle = Circle { radius: 1.0 };
#[inline(never)]
pub fn unit_shape() -> &'static dyn Shape {
&UNIT
}
$ rustc --edition 2021 -O --crate-type=lib -C symbol-mangling-version=v0 --emit=asm vtable2.rs
$ grep -A3 '^l_anon.*\.0:' vtable2.s
l_anon.60c15bf517e2d5c696fd7e336c057abe.0:
.asciz "\000\000\000\000\000\000\000\000\b\000\000\000\000\000\000\000\b\000\000\000\000\000\000"
.quad __RNvXCs1umv6GY0ZL6_7vtable2NtB2_6CircleNtB2_5Shape4area
.quad __RNvYNtCs1umv6GY0ZL6_7vtable26CircleNtB4_5Shape8describeB4_
The .asciz line is 24 bytes including its trailing zero byte: three 8-byte slots. The first is 0, and the second and third are 8 (\b). Demangled with nm -C, the two .quad entries after it are <Circle as Shape>::area and <Circle as Shape>::describe. The default method describe also got a Circle-specific copy, and that copy went into the vtable.
The first three slots are what the DynMetadata docs list as vtable contents: a drop function pointer, the size, and the alignment. Circle is a single f64, so its size and alignment are 8. My reading of the zero in the drop slot is that Circle has nothing to drop, so no function address was stored. This slot order is not a format the language guarantees; it is what rustc 1.94.1 produced.
Comparing the call paths
To see how the vtable shows up in call cost, I compiled a function taking &Circle next to one taking &dyn Shape.
pub trait Shape {
fn area(&self) -> f64;
}
pub struct Circle {
pub radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.radius * self.radius
}
}
#[inline(never)]
pub fn area_static(shape: &Circle) -> f64 {
shape.area()
}
#[inline(never)]
pub fn area_dyn(shape: &dyn Shape) -> f64 {
shape.area()
}
This is the --emit=asm output with assembler directives such as .cfi and labels filtered out.
__RNvCsYsckr2IOkS_8dispatch11area_static:
ldr d0, [x0]
mov x8, #34079
movk x8, #20971, lsl #16
movk x8, #7864, lsl #32
movk x8, #16393, lsl #48
fmov d1, x8
fmul d1, d0, d1
fmul d0, d0, d1
ret
__RNvCsYsckr2IOkS_8dispatch8area_dyn:
ldr x1, [x1, #24]
br x1
No call to Circle::area remains in area_static. The compiler inlined the body: it loads radius, builds the constant 3.14, and does two multiplications. Inside the generic print_area::<Circle>, shape.area() is likewise fixed at compile time and can be inlined the same way. area_dyn takes the vtable pointer (x1) out of its two incoming pointers, loads the slot at offset 24 of the vtable, and branches to that address. Offset 24 is the first method, area, right after the drop, size, and align slots from the previous section.
area_dyn itself is two instructions, but the body of Circle::area still runs separately after the branch. Because the function to call is decided at run time, area cannot be inlined into area_dyn. The Rust Book makes the same point: dynamic dispatch prevents inlining, and with it some optimizations. This example pins the function boundary with #[inline(never)]. When the caller can see the concrete type, the optimizer may remove the indirect call. In code that calls a small method through dyn inside a loop, I think that difference adds up. I did not measure run time.
Holding several types in one collection
A Vec<T> has exactly one element type T. Putting a Circle and a Rect in the same Vec fails with E0308 right at the vec!.
// Shape, Circle, Rect are the same as above
fn total_area<T: Shape>(shapes: &[T]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
let shapes = vec![Circle { radius: 1.0 }, Rect { width: 2.0, height: 3.0 }];
println!("{}", total_area(&shapes));
}
error[E0308]: mismatched types
--> hetero_err.rs:31:47
|
31 | let shapes = vec![Circle { radius: 1.0 }, Rect { width: 2.0, height: 3.0 }];
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Circle`, found `Rect`
Making the element type Box<dyn Shape> makes it compile. Each value is placed separately on the heap, and the Vec holds pointer pairs that are 16 bytes whatever type they point to.
// Shape, Circle, Rect are the same as above
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 { radius: 1.0 }),
Box::new(Rect { width: 2.0, height: 3.0 }),
];
println!("{:.2}", total_area(&shapes));
println!("Box<dyn Shape> = {} bytes", std::mem::size_of::<Box<dyn Shape>>());
}
9.14
Box<dyn Shape> = 16 bytes
Each element carries the vtable address for its own type, so total_area calls the right area without knowing what each element is. Heap allocation through Box is outside the scope of this post.
impl Trait in argument and return position
In argument position, fn print_area(shape: &impl Shape) is what The Rust Reference calls syntactic sugar for <T: Shape>. Monomorphization happens the same way. The difference is that the type parameter has no name, so a caller cannot spell out the type as in print_area::<Circle>(…).
In return position, -> impl Shape means “this function returns some single type that implements Shape.” The function picks that type, and the caller uses only Shape methods without knowing its name. It has to be one type, though. Returning a different type depending on the input is rejected.
// Shape, Circle, Rect are the same as above
fn parse_shape(spec: &str) -> impl Shape {
if spec == "circle" {
Circle { radius: 1.0 }
} else {
Rect { width: 2.0, height: 3.0 }
}
}
fn main() {
println!("{}", parse_shape("circle").area());
}
error[E0308]: `if` and `else` have incompatible types
--> impl_ret_err.rs:30:9
|
27 | / if spec == "circle" {
28 | | Circle { radius: 1.0 }
| | ---------------------- expected because of this
29 | | } else {
30 | | Rect { width: 2.0, height: 3.0 }
| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `Circle`, found `Rect`
31 | | }
| |_____- `if` and `else` have incompatible types
|
help: you could change the return type to be a boxed trait object
|
26 - fn parse_shape(spec: &str) -> impl Shape {
26 + fn parse_shape(spec: &str) -> Box<dyn Shape> {
|
help: if you change the return type to expect trait objects, box the returned expressions
|
28 ~ Box::new(Circle { radius: 1.0 })
29 | } else {
30 ~ Box::new(Rect { width: 2.0, height: 3.0 })
|
impl Shape hides one concrete type fixed at compile time. No copies are made, but it cannot express a type that depends on run-time values. The compiler suggests switching to Box<dyn Shape>. A function whose return type is always the same can keep impl Shape.
// Shape, Circle, Rect are the same as above
fn parse_shape(spec: &str) -> Box<dyn Shape> {
if spec == "circle" {
Box::new(Circle { radius: 1.0 })
} else {
Box::new(Rect { width: 2.0, height: 3.0 })
}
}
fn unit_circle() -> impl Shape {
Circle { radius: 1.0 }
}
fn main() {
println!("{:.2}", parse_shape("circle").area());
println!("{:.2}", parse_shape("rect").area());
println!("{:.2}", unit_circle().area());
}
3.14
6.00
3.14
Dyn compatibility: traits that can have a vtable
Not every trait can be used as dyn. A vtable has one slot per method for each concrete type, and if some method cannot get a slot and is not excluded with where Self: Sized, the trait cannot be used as dyn. This post covers only the two common method cases. The full rules are in the dyn compatibility section of the Reference. This property used to be called object safety; a compiler change that shipped in Rust 1.83 renamed it to dyn compatibility.
Adding a method that returns Self makes code using &dyn Shape fail to compile.
trait Shape {
fn area(&self) -> f64;
fn scaled(&self, factor: f64) -> Self;
}
fn print_area(shape: &dyn Shape) {
println!("{}", shape.area());
}
fn main() {}
error[E0038]: the trait `Shape` is not dyn compatible
--> dyn_compat_err.rs:6:23
|
6 | fn print_area(shape: &dyn Shape) {
| ^^^^^^^^^ `Shape` is not dyn compatible
|
note: for a trait to be dyn compatible it needs to allow building a vtable
for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
--> dyn_compat_err.rs:3:38
|
1 | trait Shape {
| ----- this trait is not dyn compatible...
2 | fn area(&self) -> f64;
3 | fn scaled(&self, factor: f64) -> Self;
| ^^^^ ...because method `scaled` references the `Self` type in its return type
= help: consider moving `scaled` to another trait
The concrete type behind a dyn Shape is known only at run time. If scaled were called through dyn, the caller could not know at compile time whether it gets back a Circle or a Rect, or how many bytes to make room for. A type parameter on a method triggers the same E0038. Changing the method to fn scale_by<F: Into<f64>>(&self, factor: F) reports the reason as ...because method `scale_by` has generic type parameters: each F would need its own copy, while a vtable’s slots must be fixed in advance.
Adding where Self: Sized to a method leaves just that method out of the vtable, and the trait can be used as dyn again.
trait Shape {
fn area(&self) -> f64;
fn scaled(&self, factor: f64) -> Self
where
Self: Sized;
}
// Circle and impl Shape for Circle (including scaled) omitted
fn print_area(shape: &dyn Shape) {
println!("{:.2}", shape.area());
}
fn main() {
let circle = Circle { radius: 1.0 };
let bigger = circle.scaled(2.0);
print_area(&circle);
print_area(&bigger);
}
3.14
12.56
scaled can only be called where the concrete type is known, as with circle. Calling shape.scaled(2.0) on a &dyn Shape fails with the `scaled` method cannot be invoked on a trait object. Extracting this trait’s vtable the same way as before shows a single area slot after the drop, size, and align slots.
$ grep -A2 '^l_anon.*\.0:' vtable_sized.s
l_anon.9b7a0b330995a7234a55b9e0bc8ba3fc.0:
.asciz "\000\000\000\000\000\000\000\000\b\000\000\000\000\000\000\000\b\000\000\000\000\000\000"
.quad __RNvXCsfxFx7uliNFX_12vtable_sizedNtB2_6CircleNtB2_5Shape4area
Choosing between them
I think generics or impl Trait are the right default. The implementation to call is fixed at compile time, and inlining stays possible. I decide whether dyn is needed with the three questions in the diagram.
- When types must be mixed. This is the case of holding different concrete types in one
Vec,HashMap, or struct field. If the set of types is closed, an enum can group them, but when the set is open, as with plugins or event handlers,dynis required. - When the return type is decided at run time. A function that returns a different type depending on configuration or input cannot be written with
impl Trait. If the possible types are a known few, an enum can group them. Otherwise it returnsBox<dyn Trait>. - When the copies become a burden. Calling a large, widely used generic function with many types compiles the same body once per type, growing build time and binary size. I did not measure that size in this post. If it is the problem, consider
dynto bring the copies down to one, or let the generic function only convert its arguments and hand the body to a non-generic function. Conversely, a small method called often inside a loop is better kept generic so it can be inlined.
Whichever reason applies, choosing dyn requires the trait to be dyn compatible. Methods that return Self or take type parameters get where Self: Sized to stay out of the vtable, or move to a separate trait.
Wrapping up
Generics fix the type at compile time and make a copy of the function for each type they are called with. The separate print_area::<Circle> and print_area::<Rect> entries in nm were that copying. Return-position impl Trait makes no copies; it hides a single type. dyn Trait is a fat pointer made of a value pointer and a vtable pointer, and it reads the method address from the vtable at run time. The extra instructions I saw in area_dyn were ldr x1, [x1, #24] and br x1, and in exchange area cannot be inlined there. Whether a trait can be used as dyn at all also comes down to whether a vtable can be built for it.
When types must be mixed in one place, or the return type depends on run-time values, dyn is required. Only otherwise does it come to weighing the cost of extra copies against the cost of indirect calls. I see the choice as deciding how many copies of a function to compile, and when to decide which implementation runs.
References
- Rust Closures and Iterators: the Fn, FnMut, and FnOnce bounds for closures, and iterator adapters
- Rust Lifetimes: lifetime annotations in signatures and the
T: 'staticbound - Rust References and Borrowing: the size of the slice reference
&str, which carries a pointer and a length - The Rust Reference — Trait objects
- The Rust Reference — Dyn compatibility
- The Rust Reference — Impl trait
- The Rust Programming Language — Using Trait Objects to Abstract over Shared Behavior
std::ptr::DynMetadata- rustc codegen options — symbol-mangling-version