Abstractions in Practice · 18 min · free with an account

Trait Objects

Lesson preview · about 30%

Choose behavior at runtime with dyn Trait.

Core idea

A trait object stores a pointer to data and a table of methods.

Start with the idea

A trait object stores a pointer to data and a table of methods. It enables mixed concrete types in one collection at the cost of dynamic dispatch and some optimization opportunities.

A trait object lets code work with a value whose concrete type is chosen at runtime. Box<dyn Draw> owns a value on the heap while exposing only the Draw behavior. A vector of these boxes can contain buttons, charts, and labels as long as each implements Draw. A generic Vec<T> normally has one concrete T for all entries, so it cannot directly hold several unrelated structs. The trait object is the bridge when a heterogeneous collection is genuinely needed.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery