Recall & Review
beginner
What is a trait object in Rust?
A trait object is a way to use traits for dynamic dispatch, allowing you to call methods on types that implement a trait without knowing the exact type at compile time.
Click to reveal answer
beginner
How do you create a trait object in Rust?
You create a trait object by using a reference or a pointer to a type that implements a trait, like &dyn Trait or Box<dyn Trait>.
Click to reveal answer
intermediate
Why use trait objects instead of generics?
Trait objects allow for dynamic dispatch and can store different types that implement the same trait in one variable, while generics use static dispatch and require knowing the type at compile time.
Click to reveal answer
intermediate
What is dynamic dispatch in the context of trait objects?
Dynamic dispatch means the program decides at runtime which method implementation to call based on the actual type behind the trait object.
Click to reveal answer
advanced
Can trait objects be used with traits that have generic methods?
No, trait objects cannot be created from traits with generic methods because the compiler needs to know the exact types to perform dynamic dispatch.
Click to reveal answer
Which syntax correctly creates a trait object for a trait named `Draw`?
✗ Incorrect
The correct syntax for a trait object reference is &dyn Trait, so &dyn Draw is correct.
What does dynamic dispatch mean when using trait objects?
✗ Incorrect
Dynamic dispatch means the program decides which method to call at runtime based on the actual type.
Why can't trait objects be used with traits that have generic methods?
✗ Incorrect
Generic methods require the compiler to know exact types, which trait objects cannot provide for dynamic dispatch.
Which of these is a benefit of using trait objects?
✗ Incorrect
Trait objects allow storing different types that implement the same trait in one variable using dynamic dispatch.
What is the main difference between trait objects and generics?
✗ Incorrect
Trait objects use dynamic dispatch to decide method calls at runtime, while generics use static dispatch at compile time.
Explain what a trait object is and how it enables dynamic dispatch in Rust.
Think about how Rust calls methods when the exact type is not known at compile time.
You got /3 concepts.
Describe the main differences between using trait objects and generics in Rust.
Consider when you want flexibility versus performance.
You got /4 concepts.