Recent Rust changes have made "trait objects" more prominent to me, but I only have a nebulous grasp of what actually makes something into a trait object. One change in particular is the upcoming change to allow trait objects to forward trait implementations to the inner type.
Given a trait Foo
, I'm pretty sure that Box<Foo>
/ Box<dyn Foo>
is a trait object. Is &Foo
/ &dyn Foo
also a trait object? What about other smart-pointer things like Rc
or Arc
? How could I make my own type that would count as a trait object?
The reference only mentions trait objects once, but nothing like a definition.
You have trait objects when you have a pointer to a trait.
Box
,Arc
,Rc
and the reference&
are all, at their core, pointers. In terms of defining a "trait object" they work in the same way."Trait objects" are Rust's take on dynamic dispatch. Here's an example that I hope helps show what trait objects are:
For further reference, there is a good Trait Objects chapter of the Rust book