IT lexicon › Programming › Trait objects

Trait objects

Programming På svenska → Updated: 2026-07-29

Rust's way of doing dynamic dispatch: dyn Trait hides the concrete type and looks the method up in a vtable at runtime.

Generic code in Rust is normally monomorphized — the compiler stamps out a separate copy per concrete type, giving direct calls but growing binaries. Sometimes that isn't possible: a vector meant to hold several different kinds of shape cannot have one concrete element type. That is where Box<dyn Draw> comes in, with each value represented by a pair of pointers — one to the data, one to the table of that type's method implementations. The call becomes indirect and cannot be inlined, but the code exists in exactly one copy. Not every trait qualifies: object safety rules exclude generic methods among others, since a vtable cannot be filled with infinitely many variants.

← Back to the lexicon