Skip to main content
Module 10 · Lesson 2 of 422/24 in the course~20 min
Module lessons (2/4)

Dynamic Dispatch (Box<dyn Trait>) & Object Safety

Lesson preview5 hands-on exercises readyCourse Rust · Module 10 — Advanced Traits and Fearless Concurrency

Comparison between static generics <T: Trait> and Box<dyn Trait> (vtable), heterogeneous collections and dyn-compatibility requirements.

What you'll learn in this lesson

  • Make an informed choice between static dispatch (<T: Trait>) and dynamic dispatch (dyn Trait).
  • Construct heterogeneous collections (Vec<Box<dyn Shape>>) that contain different concrete types at runtime.
  • Recognize the dyn-compatibility (ex object safety) rules of a trait.

Overview

Up until Module 5 we used <T: Summary> (static dispatch): the compiler knows the exact type of T at compilation. But what to do if you want a Vec that mixes a Circle, a Rect and a Triangle in the same vector, known only by reading a file at runtime? You need a Trait Object (dyn Trait).

A reference &dyn Shape or a smart pointer Box<dyn Shape> is a fat pointer 2 machine words large:

Sections covered in this lesson

  1. 11. How Box<dyn Trait> (Fat Pointer) works
  2. 22. Static vs Dynamic Dispatch compared
  3. 33. Dyn-Compatibility (formerly Object Safety)
  4. 44. Conditional dynamic return with Box<dyn Error>
  5. 5Practical exercises
  6. 6Check for understanding
Pro Lesson · Module 10 — Advanced Traits and Fearless Concurrency

Unlock "Dynamic Dispatch (Box<dyn Trait>) & Object Safety" and the full Course Rust curriculum

Comparison between static generics `<T: Trait>` and `Box<dyn Trait>` (vtable), heterogeneous collections and dyn-compatibility requirements.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Rust plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.