Associated types
An associated type is a type placeholder a trait implementor fills in once, such as Iterator::Item. Callers name it as T::Item instead of adding another generic parameter.
Detailed Explanation
trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } says every iterator produces one kind of item. impl Iterator for Counter { type Item = u32; ... } fills it in. There is only one Item per implementation. That is the difference from a generic trait trait Iterator<Item>. A type can implement Iterator<Item = u32> and Iterator<Item = String> if Item is a parameter; it can implement Iterator only once if Item is associated.
Associated types are the right shape when the related type is determined by the implementor, not chosen by the caller. An iterator knows what it yields. A graph knows what its node id is. An error-producing trait knows its Error type. The caller writes T::Item or <T as Iterator>::Item and does not pass a second type parameter through every function.
You bound associated types in where clauses: where T: Iterator, T::Item: Debug. You can require a specific associated type: T: Iterator<Item = u32>. That is a bound, not an assignment. The implementor already chose Item; you are saying you only accept implementors who chose u32.
Generic associated types (GATs) let the associated type take parameters: type Item<'a>; on a lending iterator, where each next returns a borrow of the iterator itself. You reach for a GAT when the associated type needs a lifetime or a type parameter that is not an input to the trait as a whole.
Why not make everything generic: fn collect<I, T>(iter: I) -> Vec<T> where I: Iterator<T> does not compile that way, and even if it did, every helper would grow another parameter. Associated types keep the extra type attached to I instead of threaded through the stack.
When you write an associated type: each implementor has exactly one right choice for that type. When callers must pick the type independently of the implementor, a generic parameter on the trait is correct (From<T> is generic because a type can be created from many sources).
Code Examples
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}
impl<T> Container for Vec<T> {
type Item = T;
fn first(&self) -> Option<&T> {
self.get(0)
}
}
fn print_first<C>(c: &C)
where
C: Container,
C::Item: std::fmt::Debug,
{
println!("{:?}", c.first());
}
fn main() {
print_first(&vec![10, 20]); // prints: Some(10)
}Common Gotchas
One impl, one associated type
A type cannot implement `Iterator` twice with two `Item`s. If you need two item types, you need two traits or a generic trait.
Do not genericise a trait that wants an associated type
`trait Iter<T>` lets a type implement the trait many times and makes every use site write `T`. Prefer `type Item` when the item is inherent.
Name it with UFCS when inference stalls
`<C as Container>::Item` is the fully qualified form. Use it in struct fields and tangled bounds.
GATs are powerful and heavy
A lending iterator is the textbook GAT. Do not add a generic associated type because it looks advanced; a generic method may suffice.