IT lexicon › Programming › Trait object

Trait object

Programming På svenska → Updated: 2026-05-27

Rust feature: dynamic dispatch via virtual table. Box<dyn Trait> or &dyn Trait. Runtime polymorphism instead of compile-time monomorphization. Trade-off: bigger flexibility, slight runtime cost.

Vtable lookup: ~5ns per method call vs inlined static dispatch ~0ns. Mostly negligible — use trait objects when: heterogeneous collections (Vec<Box<dyn Trait>>), plugin architectures, returning different concrete types via a function. Object-safety rules: trait can be object if all methods are dispatchable (no Self-by-value, no generic method args). Modern Rust 1.27+: dyn keyword mandatory (vs old "&Trait" syntax). Equivalent: Java interface (always virtual), Go interface (same). Trait objects + monomorphization are complementary patterns; choose based on need.

← Back to the lexicon