skip to content

In Rust, what does a `&dyn Shape` hold at run time, and what does a method call through it cost versus a generic call?

level: middleimportance: must knowfreq 62%

answer

  1. two words, not one
  2. data pointer plus table pointer
  3. size, align, drop, then methods
  4. indirect call, no inlining

basics

~20 s

A pointer to dyn Shape is a fat pointer: a data pointer plus a vtable pointer, the vtable holding size, alignment, drop glue and method pointers. Each call is indirect through it and generally not inlined; generics compile a direct call per type.

solid answer

~40 s

`&dyn Shape` and `Box<dyn Shape>` are **wide pointers**, twice the size of `&Circle`: 16 bytes on a 64-bit target. The first word points at the value; the second points at a **vtable** the compiler generated for that concrete type's `Shape` impl, holding its size, alignment, a pointer to its `drop_in_place`, and one function pointer per `Shape` method (supertrait methods included). The vtable lives in static memory, not in the object. `s.area()` loads the `area` pointer from the vtable and calls through it, so the call is indirect and generally cannot be inlined. A generic `fn total<T: Shape>` is monomorphized: each `T` gets its own copy with direct, inlinable calls, at the cost of more code. `size_of_val` and dropping a `Box<dyn Shape>` read size, alignment and drop glue from the vtable.

code

rust · 23 lines
rust
use std::mem::{size_of, size_of_val};

trait Shape { fn area(&self) -> f64; }
struct Circle { r: f64 }
#[allow(dead_code)] // label only adds size here
struct Rect { w: f64, h: f64, label: String }
impl Shape for Circle { fn area(&self) -> f64 { 3.14 * self.r * self.r } }
impl Shape for Rect { fn area(&self) -> f64 { self.w * self.h } }

fn main() {
    println!("&Circle:        {}", size_of::<&Circle>());
    println!("&dyn Shape:     {}", size_of::<&dyn Shape>());
    println!("Box<dyn Shape>: {}", size_of::<Box<dyn Shape>>());

    let canvas: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle { r: 1.0 }),
        Box::new(Rect { w: 2.0, h: 3.0, label: String::from("door") }),
    ];
    for s in &canvas {
        // size_of_val reads the size stored in each value's vtable
        println!("{:.2} area, {} bytes behind the pointer", s.area(), size_of_val(&**s));
    }
}

go deeper

for a junior

Recall that a trait object pointer is two words, data and vtable, and that a call through it is resolved at run time rather than compile time.

for a middle

List what the vtable holds: size, alignment, drop_in_place, then method pointers. Explain how Box<dyn Shape> drops and frees a value it cannot name.

for a senior

Put the cost where it belongs: lost inlining and scattered heap data, not the indirect call itself. Know how ?Sized lets generic code accept a trait object.

for a principal

Treat dispatch as a profile-driven choice per hot path: one compiled copy and open extension against inlining and code size, and set the expectation that it is measured.

## Two words instead of one A reference to a sized type, `&Circle`, is one machine word: an address. A reference to a trait object is a **wide pointer** (often called a *fat pointer*). The Reference states that pointers to dynamically sized types are twice the size of pointers to sized types, because they also store **metadata**; for a trait object the metadata is a pointer to a vtable. On a 64-bit target: | Type | Size | Contents | |---|---|---| | `&Circle` | 8 bytes | address of the circle | | `&dyn Shape` | 16 bytes | address of the value + address of its vtable | | `Box<dyn Shape>` | 16 bytes | heap address + vtable address | | `&[u8]` | 16 bytes | address + length (a slice's metadata) | `Rc<dyn Shape>`, `Arc<dyn Shape>` and raw `*const dyn Shape` carry the same pair. ## What is in the vtable The core library describes the vtable as notably containing: - the concrete type's **size**; - its **alignment**; - a pointer to its **`drop_in_place`** implementation (a no-op for plain data); - **pointers to every method** of the trait's implementation for that type, including the supertraits' methods. The first three are what any owner needs to allocate, drop and free a value it cannot name. That is how `Box<dyn Shape>` frees a `Rect`'s `String` label correctly, and how `std::mem::size_of_val(&**s)` reports 8 bytes for a circle and 40 for a labelled rectangle in the same `Vec`. The vtable is emitted at compile time for each concrete type the program coerces to `dyn Shape`, and it lives in **static memory**: a `Box<dyn Shape>` pointing at a circle points at a circle vtable rather than carrying its own, and the circle itself carries no hidden header. (C++ embeds a vtable pointer inside each polymorphic object; Rust puts it in the pointer.) Do not rely on vtable addresses being unique: the core docs warn that vtables can be duplicated across codegen units and identical ones merged, so comparing two `*const dyn Shape` pointers with `ptr::eq` is unreliable. ## What a call costs A call `s.area()` through a trait object is **dynamic dispatch**: 1. read the vtable pointer from the wide pointer; 2. load the `area` slot from the vtable; 3. make an indirect call through it, passing the data pointer as `self`. The direct costs are small: an extra load and an indirect branch the CPU must predict. The larger cost is what the optimizer loses. As the Rust Book puts it, dynamic dispatch prevents the compiler from choosing to inline the method's code, which in turn prevents optimizations that would follow from inlining, for example vectorizing a loop over the areas. Heap-allocated boxes also scatter the shapes in memory. A generic `fn total<T: Shape>(shapes: &[T]) -> f64` is **statically dispatched**. Monomorphization compiles one copy of `total` per concrete `T`, each with direct, inlinable calls to that type's `area`. The price is code size and compile time, a copy per type; the trait object compiles `total(&[Box<dyn Shape>])` once. | | `&dyn Shape` / `Box<dyn Shape>` | `T: Shape` | |---|---|---| | Resolved | at run time, via vtable | at compile time | | Copies of the caller | one | one per concrete type | | Inlining | generally lost at the call | available | | Mixed types in one collection | yes | no | ## Bridging the two `dyn Shape` automatically implements `Shape`, so a generic function can accept a trait object, but only if it opts out of the implicit `Sized` bound: `fn report<T: Shape + ?Sized>(s: &T)` accepts `&*boxed`, while `fn report<T: Shape>(s: &T)` rejects it with **E0277**, "the size for values of type `dyn Shape` cannot be known at compilation time". ## When the cost matters - For a plugin list, an event handler table or a canvas redrawn sixty times a second with a few hundred shapes, the indirect call is noise next to the drawing itself. - In a tight numeric loop over millions of elements, the lost inlining can dominate; group the elements by concrete type, use an enum, or keep the loop generic. - Measure before rewriting: the difference shows up in profiles, not in reasoning about one call.

  • Why does `fn report<T: Shape>(s: &T)` reject `&*boxed` when `boxed` is a `Box<dyn Shape>`?
    Generic parameters carry an implicit `Sized` bound, and `dyn Shape` is unsized, so rustc reports E0277 "the size for values of type `dyn Shape` cannot be known at compilation time". Writing `T: Shape + ?Sized` lifts the bound; since `dyn Shape` implements `Shape`, the function then accepts a trait object as well as concrete shapes.
  • Is a vtable built at run time when you create a `Box<dyn Shape>`?
    No. The compiler emits the vtable for each concrete type and trait pair it coerces, as static data. Creating the box only allocates the value and writes the two words: the heap address and the address of the existing vtable. Nothing in the object itself changes.
  • Can you test whether two `&dyn Shape` refer to the same shape by comparing the pointers?
    Not reliably with the wide pointers. The core docs warn that vtables of the same type can be duplicated across codegen units and identical vtables of different types merged, so `ptr::eq` on `*const dyn Shape` may give either answer. Compare only the data addresses, `ptr::addr_eq`, when identity is what you mean.

A trait object is a parcel with a delivery slip taped to the outside: the box holds the goods, and the slip says how heavy it is and who handles returns. Anyone can process the parcel by reading the slip, but nobody can plan ahead for what is inside.

  • Says a trait object reference is one pointer, like a reference to a concrete type.
  • Believes each Shape value stores a hidden vtable pointer inside itself.
  • Thinks the vtable is built at run time each time a Box<dyn Shape> is created.
  • Claims dynamic dispatch is free because the indirect call is only one load.
  • Says generics avoid all cost, ignoring the extra code each instantiation adds.