Skip to main content

Trait objects and dynamic dispatch

Generics pick one concrete type per call site. When you need a single collection holding several different types that all implement a trait, you need a trait object: `Box<dyn Shape>` or `&dyn Shape`.

That flexibility costs one pointer indirection at call time — the vtable lookup. It is small, and it is the only time Rust adds runtime dispatch without you asking.

`impl Trait` in a return position is the middle ground: the caller gets a single concrete type without you naming it, still statically dispatched.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust