Sub topic 7
Associated types behind dyn Trait
This chapter assumes you can write a trait with an associated type, bound it with Iterator<Item = T>, and use Box<T> for heap values. It covers what changes when you use such a trait as a trait object.
Why dyn needs the associated type
A trait object, written dyn Trait, calls methods through a vtable. That is a table of function pointers built for one concrete type. The compiler must know every method signature in the table. If a method returns Option<&Self::Item>, the compiler must know what Item is.
For that reason, a dyn type has to name each associated type in angle brackets. The syntax is the same as the bound Iterator<Item = u32> you already know.
fn evens(limit: u32) -> Box<dyn Iterator<Item = u32>> {
Box::new((0..limit).filter(|n| n % 2 == 0))
}
fn main() {
for n in evens(7) {
println!("{}", n);
}
}This prints 0, 2, 4 and 6. The caller sees only "something that yields u32". The Filter<Range<u32>, _> type stays hidden.
Mixing different implementers
A trait object is useful when branches return different concrete types. An if expression cannot return both Rev<RangeInclusive<u32>> and RangeInclusive<u32>. Boxing both as dyn Iterator<Item = u32> makes them one type.
fn numbers(descending: bool) -> Box<dyn Iterator<Item = u32>> {
if descending {
Box::new((1..=3).rev())
} else {
Box::new(1..=3)
}
}
fn main() {
let v: Vec<u32> = numbers(true).collect();
println!("{:?}", v);
}The program prints [3, 2, 1].
The same works with your own traits. Here two unrelated types share one Vec, because both fix Item to i32.
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}
struct Stack<T> {
items: Vec<T>,
}
impl<T> Container for Stack<T> {
type Item = T;
fn first(&self) -> Option<&Self::Item> {
self.items.first()
}
}
struct Single(i32);
impl Container for Single {
type Item = i32;
fn first(&self) -> Option<&i32> {
Some(&self.0)
}
}
fn main() {
let boxes: Vec<Box<dyn Container<Item = i32>>> = vec![
Box::new(Stack { items: vec![10, 20] }),
Box::new(Single(7)),
];
for b in &boxes {
println!("{:?}", b.first());
}
}The output is Some(10) and then Some(7). A Stack<String> would not fit in this Vec, because its Item is String, not i32.
The common error
If you write Box<dyn Container> and leave out Item, the compiler reports error E0191: the value of the associated type Item in Container must be specified. Fix it by writing dyn Container<Item = i32>. You cannot leave the type open, because the vtable has no way to represent "any Item".
Limits of dyn with associated types
Associated types do not by themselves stop a trait from being used as dyn. Other features do.
| Feature in the trait | Effect on `dyn Trait` |
|---|---|
| Plain associated type | Allowed, but you must name it in every `dyn` type |
| Method with its own type parameter | Not callable on `dyn`, unless marked `where Self: Sized` |
| Method returning `Self` | Same, needs `where Self: Sized` |
| Generic associated type (GAT) | The trait is not dyn compatible |
The last row matters for the next chapters. A LendingIterator with type Item<'a> cannot be used as Box<dyn LendingIterator>. A GAT stands for a whole family of types, and a vtable can hold only one. If you need runtime dispatch over such a trait, use generics or impl Trait in argument position. You can also reshape the API so it takes a callback instead of returning borrowed items.
Exercise
Why does fn f() -> Box<dyn Container> fail to compile when Container has type Item;, and what is the fix?
Show answer
A trait object needs a fixed vtable, so the compiler must know the concrete type of every associated type. Without Item, it reports E0191. Name it: Box<dyn Container<Item = i32>>.