Sub topic 2
Associated Type or Generic Parameter?
Assume you know how to define traits, write generic functions, use trait bounds, and borrow values with lifetime annotations.
Associated type or generic parameter?
An associated type is a type chosen by each implementation of a trait:
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()
}
}Stack<T> has one Item type for each implementation. The relationship is fixed by the implementer.
Use a generic trait parameter when one type should support several implementations for different related types:
trait Convert<Target> {
fn convert(self) -> Target;
}A type can implement Convert<String> and Convert<Vec<u8>> separately. With an associated type, each trait implementation has only one chosen output type.
| Design choice | Best fit |
|---|---|
| One fixed related type per implementation | Associated type |
| Several implementations for different related types | Generic trait parameter |
Naming associated types
Inside a generic function, use C::Item:
fn first_item<C: Container>(container: &C) -> Option<&C::Item> {
container.first()
}Outside that context, use a fully qualified path such as <Stack<u32> as Container>::Item. This names the Item selected by the Container implementation for Stack<u32>.
Associated types behind `dyn Trait`
A trait object, written as dyn Trait, hides the concrete implementing type. Associated types must usually be specified so dynamic code knows which type to expect:
fn numbers() -> Box<dyn Iterator<Item = u32>> {
Box::new(1..=3)
}Box<dyn Iterator> is incomplete because Iterator::Item is unspecified. The same rule applies to custom traits, such as dyn Container<Item = u32>.
Traits with generic associated types are generally not usable as dyn Trait, because the object would need to support the entire family of associated types.
The lending iterator problem
A plain Iterator has one Item type. It cannot express an item whose lifetime is tied to the particular borrow used by next.
A lending iterator needs a generic associated type, or GAT:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}Here, Item<'a> can be a mutable reference valid for the borrow of self. This supports overlapping windows and other APIs that return data borrowed from the iterator itself.
Exercise
Why can a trait use a generic parameter instead of an associated type?
Show answer
A generic parameter allows multiple implementations for different related types, while an associated type fixes one related type for each implementation.