Trait objects
Now, up until this point, we have mostly seen traits being used in a static dispatch context, where we specified trait bounds in generic APIs. However, we also have another way to create polymorphic APIs, where we can specify parameters as something that implements a trait rather than a generic or a concrete type. This form of type, specified as implementing a trait API, is known as a trait object. Trait objects are similar to C++ virtual methods. A trait object is implemented as a fat pointer and is an unsized type, which means that they can only be used behind references (&). We explain unsized types in Chapter 7, Advanced Concepts. A trait object fat pointer has the first pointer pointing points to the actual data associated ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access