Module lessons (2/4)
Dynamic Dispatch (Box<dyn Trait>) & Object Safety
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
- 11. How
Box<dyn Trait>(Fat Pointer) works - 22. Static vs Dynamic Dispatch compared
- 33. Dyn-Compatibility (formerly Object Safety)
- 44. Conditional dynamic return with
Box<dyn Error> - 5Practical exercises
- 6Check for understanding
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.