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+?

- 30,736
- 10
- 83
- 104
1 Answers
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.

- 388,571
- 95
- 1,107
- 1,366

- 27,633
- 5
- 85
- 95
-
1Probably worth being specific about the usage of "trait object" here. I think most people would lazily call `Box
` a "trait object" and that can be put in a `Vec`. – Shepmaster Jul 05 '19 at 14:47