Reputation: 31323
In the Rust Edition Guide it says that in Rust 1.2, more container types support trait objects. It gave the example of Rc<T>
, but it didn't give a complete list. What other containers support trait objects in Rust 1.2+?
Upvotes: 1
Views: 330
Reputation: 30061
Containers that support trait objects are containers that have a ?Sized
bound on their containee type.
By default with generics, all types are Sized
implicitly as this is what you want most of the time, and adding a Sized
on almost every generic would be annoying. This behaviour is different from other traits and can be avoided by adding a ?Sized
bound.
struct Foo<T>; // implicit `T: Sized` bound. T cannot be a trait object.
struct Bat<T: ?Sized>; // T can be a trait object.
You can see on the repository that Rc
indeed used to be declared pub struct Rc<T>
and was later changed to pub struct Rc<T: ?Sized>
. GitHub lists this change as being part of Rust 1.1, but I guess we had to wait 1.2 to get it in stable.
Other containers that work on trait objects are Box
, Arc
, Cell
and all the like of those smart pointers.
Containers that do not work on trait objects are Vec
, HashMap
and generally containers that might store more that one instance (collections). This is because 2 instances of the same trait objects might have different sizes (if they have different concrete type), and collections usually store elements continuously, requiring a constant size.
Upvotes: 3