0PricingLogin
Learn Rust Coding · Lesson

Trait Objects and dyn

Dynamic dispatch.

The Problem: Mixed Types

Generics with trait bounds work great when each call uses one concrete type. But what if you want a collection of different types that all share a trait? Generics cannot hold a mix.

Trait objects solve this.

What Is a Trait Object?

A trait object is a value referred to through a pointer plus the keyword dyn, like &dyn Trait or Box<dyn Trait>.

It lets you treat many concrete types uniformly at runtime.

All lessons in this course

  1. Defining Traits
  2. Trait Objects and dyn
  3. Static vs Dynamic Dispatch
  4. Default Methods
← Back to Learn Rust Coding