Sub topic 7
Associated types behind dyn Trait
This chapter assumes you can define traits, write generic functions with bounds, and use Box<dyn Trait> for simple traits. You should also know how to declare an associated type and constrain it as in I: Iterator<Item = u32>. Here you will learn what changes when a trait with associated types is used as a trait object.
The rule: every associated type must be named
A trait object erases the concrete type behind a pointer. The compiler still has to know the full type of every method signature in the trait. If a trait has an associated type, the signatures mention it, so the dyn type must fix it. You do that with the same Name = Type syntax you use in bounds.
// Does not compile: E0191, the value of the associated type `Item`
// in `Iterator` must be specified
let it: Box<dyn Iterator> = Box::new(0..3);The correct form names Item:
fn numbers(descending: bool) -> Box<dyn Iterator<Item = u32>> {
if descending {
Box::new((1..=3).rev())
} else {
Box::new(1..=3)
}
}
fn main() {
for n in numbers(true) {
print!("{n} ");
}
println!();
let total: u32 = numbers(false).sum();
println!("{total}");
}The program prints 3 2 1 and then 6. The two branches return different concrete types, Rev<RangeInclusive<u32>> and RangeInclusive<u32>. Both are boxed into the same dyn Iterator<Item = u32> type. Static impl Iterator<Item = u32> could not do this, because impl Trait in return position stands for exactly one concrete type.
Box<dyn Iterator<Item = u32>> is itself an Iterator. That is why for loops, .sum(), and adapters such as .map() work on it.
Heterogeneous collections with a fixed Item
Fixing the associated type is what lets different implementers share a collection. Types with different internals can live in one Vec as long as they agree on Item. This reuses the Container trait from the associated type basics.
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 Some(7). A Stack<String> would be rejected in this Vec, because its Item is String and not i32.
Associated types versus generic parameters in dyn types
A trait with a generic parameter, such as Convert<T>, also needs its parameter written in the dyn type, as in dyn Convert<String>. The two designs look similar at the use site, but they differ in how many trait objects can describe one type.
| Design | Trait object type | Implementations per concrete type |
|---|---|---|
| Associated type (`trait Container { type Item; }`) | `dyn Container<Item = i32>` | One. The type decides `Item`. |
| Generic parameter (`trait Convert<T>`) | `dyn Convert<String>` | Many. One per `T`. |
With an associated type, the concrete type on the other side of the pointer decides Item. The dyn type only restates a fact the compiler already knows. With a generic parameter, one concrete type can implement Convert<String> and Convert<u8>. Those are two different trait objects built from the same value.
Associated types in method arguments
Associated types can appear in argument positions, not only in returns. Once Item is fixed, the vtable has concrete signatures.
trait Sink {
type Item;
fn push(&mut self, item: Self::Item);
fn push_all<I>(&mut self, items: I)
where
Self: Sized,
I: IntoIterator<Item = Self::Item>,
{
for item in items {
self.push(item);
}
}
}
struct Log(Vec<String>);
impl Sink for Log {
type Item = String;
fn push(&mut self, item: String) {
self.0.push(item);
}
}
fn fill(sink: &mut dyn Sink<Item = String>) {
sink.push("a".to_string());
sink.push(String::from("b"));
}
fn main() {
let mut log = Log(Vec::new());
fill(&mut log);
log.push_all(vec!["c".to_string()]);
println!("{:?}", log.0);
}This prints ["a", "b", "c"]. Two details matter here:
push_allis generic overI. A vtable cannot hold one entry for every possibleI, so the method carrieswhere Self: Sized. That clause removes it from the trait object. You can callpush_allonLog, but not on&mut dyn Sink<Item = String>.- The trait stays usable as
dyn Sink<Item = String>because the generic method opts out. Without theSelf: Sizedclause, the trait would not be dyn compatible.
Supertraits and the dyn type
If an associated type comes from a supertrait, you can still name it on the subtrait's trait object. DoubleEndedIterator extends Iterator, so Item is available:
fn both_ends(it: &mut dyn DoubleEndedIterator<Item = u32>) -> (Option<u32>, Option<u32>) {
(it.next(), it.next_back())
}
fn main() {
let mut r = 1..=5u32;
println!("{:?}", both_ends(&mut r));
}The output is (Some(1), Some(5)). You write Item = u32 once, and the compiler applies it to the supertrait.
Lifetimes and auto traits on iterator objects
Two extra bounds come up often with Box<dyn Iterator<Item = ...>>.
- A lifetime bound. In a return type,
Box<dyn Trait>defaults to'static. If the iterator borrows from an argument, you must say so. - Auto traits such as
Send. These are written after the trait, joined by+.
fn evens<'a>(values: &'a [u32]) -> Box<dyn Iterator<Item = u32> + Send + 'a> {
Box::new(values.iter().copied().filter(|n| n % 2 == 0))
}
fn main() {
let data = [1, 2, 3, 4, 5, 6];
let v: Vec<u32> = evens(&data).collect();
println!("{:?}", v);
}This prints [2, 4, 6]. Without + 'a, the compiler reports that the borrowed slice does not live long enough, because it assumed 'static. Lifetimes can also appear inside the associated type itself, as in dyn Iterator<Item = &'a str> + 'a. The 'a after + bounds the object, and the 'a in Item describes what it yields. They are separate and often equal.
What makes a trait with associated types dyn compatible
Plain associated types never block dyn compatibility. These features do:
- A method that mentions
Selfoutside the receiver, for examplefn merge(self, other: Self) -> Self, unless it haswhere Self: Sized. - A generic method with type parameters, unless it has
where Self: Sized. - An associated constant.
- A generic associated type (GAT).
The last item matters for the next chapters. A lending iterator declared with type Item<'a> cannot be turned into a trait object:
// Does not compile: the trait `LendingIterator` is not dyn compatible
// because it contains the generic associated type `Item`
let it: Box<dyn LendingIterator> = ...;You cannot repair this by naming Item. A single concrete type cannot stand for Item<'a> across every lifetime 'a. The compiler has no way to write a vtable entry for "for all 'a" through a type that you must name up front. If you need type erasure over a GAT-based design, the usual workaround is a second, non-generic trait that exposes a fixed lifetime or a concrete type. Another option is to wrap the GAT trait in a small enum or a closure-based API.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| E0191, associated type must be specified | `dyn Trait` without `Name = Type` | Add `<Item = Type>` |
| Mismatched types in a `Vec<Box<dyn Trait<Item = X>>>` | An element's `Item` differs from `X` | Convert `Item`, or use an enum as `Item` |
| Borrowed value does not live long enough in a returned `Box<dyn Iterator>` | Implicit `'static` bound | Add `+ 'a` |
| Trait cannot be made into an object | Generic method, `Self` in arguments, or a GAT | Add `where Self: Sized`, or restructure |
| Method not found on a `dyn` value | The method has `where Self: Sized` | Call it on the concrete type, or remove the clause |
Exercise
A function must return either a forward or a reversed walk over a Vec<String>, chosen at runtime, and the caller will use it in a for loop. Write the return type, and say why impl Iterator<Item = String> does not work.
Show answer
Use Box<dyn Iterator<Item = String>>. If the iterator borrows from the vector instead of owning it, use Box<dyn Iterator<Item = &'a String> + 'a>. impl Iterator<Item = String> names exactly one hidden concrete type. The forward and reversed iterators are different types, so the two branches would not agree. The trait object erases the difference, and naming Item is required because Iterator has an associated type.
Exercise
A trait Parser has type Output; and a method fn parse(&self, s: &str) -> Self::Output;. You also add fn parse_many<I: Iterator<Item = String>>(&self, it: I) -> Vec<Self::Output>;. Can you still write &dyn Parser<Output = i32>? What is the smallest change that allows it?
Show answer
Not as written. parse_many is generic over I, so the trait is not dyn compatible. Adding where Self: Sized to parse_many removes it from the vtable and makes &dyn Parser<Output = i32> valid. The method then works only on concrete types. Alternatively, take &mut dyn Iterator<Item = String> as the argument, which keeps the method callable on trait objects.