Sub topic 11
Associated types
This chapter assumes you can write generic functions with trait bounds and can implement a trait for a type. It covers the type item inside a trait, when to prefer it over a second type parameter, and the errors you will most likely meet.
The problem with another type parameter
Suppose a trait describes a collection and needs to name the type of its elements. You could add a parameter to the trait:
trait ContainerOf<T> {
fn head(&self) -> Option<&T>;
}This lets one type implement ContainerOf<i32> and ContainerOf<String> at the same time. Every function that uses the trait must then also name T, even when the answer is obvious. For a collection, each implementor has exactly one natural element type, so the extra parameter adds noise and no flexibility.
Declaring an associated type
An associated type is a placeholder type declared inside the trait. Each implementation fills it in once.
trait Container {
type Item;
fn head(&self) -> Option<&Self::Item>;
}
impl<T> Container for Vec<T> {
type Item = T;
fn head(&self) -> Option<&T> {
self.first()
}
}
fn print_head<C>(c: &C)
where
C: Container,
C::Item: std::fmt::Debug,
{
println!("{:?}", c.head());
}
fn main() {
print_head(&vec![10, 20, 30]);
}Inside the trait you refer to the placeholder as Self::Item. In a bound you write C::Item. The function has one type parameter, C. The element type follows from C, and you can add bounds on it, as C::Item: Debug does here.
The standard library example
Iterator is the best-known trait with an associated type.
struct Countdown {
n: u32,
}
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.n == 0 {
None
} else {
self.n -= 1;
Some(self.n + 1)
}
}
}
fn sum_all<I>(it: I) -> u32
where
I: Iterator<Item = u32>,
{
it.sum()
}
fn main() {
for v in (Countdown { n: 3 }) {
println!("{v}");
}
println!("{}", sum_all(Countdown { n: 4 }));
}The program prints 3, 2, 1, then 10. The bound Iterator<Item = u32> accepts only iterators that yield u32. Writing the associated type this way is the usual means of constraining it.
Associated type or type parameter?
| Question | Associated type | Trait type parameter |
|---|---|---|
| Implementations per type | One | Many, one per argument |
| Caller must name it | No, it is implied | Yes, or inference must find it |
| Typical use | `Iterator`, `Deref`, `Add::Output` | `From<T>`, `PartialEq<Rhs>` |
Use an associated type when the type is determined by the implementor. Use a type parameter when one type can sensibly implement the trait several ways. String: From<&str> and String: From<char> both exist, so From needs a parameter.
Common errors
- Missing bound on the associated type. Printing
c.head()fails with a "doesn't implement Debug" error until you addC::Item: Debug. Bounds onCdo not carry over toC::Item. - Two impls of the same trait for one type. If you write a second
impl Container for Vec<u8>with a differentItem, the compiler reports conflicting implementations. The trait allows one impl per type. Switch to a trait parameter if you need several. - Forgetting the
Item = ...form.I: Iteratoralone leavesItemunknown. Writingit.sum::<u32>()then fails unlessItemis fixed.
Exercise
You are designing a trait Parser whose implementors each produce one kind of output. Should the output type be an associated type or a trait parameter, and why?
Show answer
An associated type. Each parser has one output type, so the implementation fixes it once, and callers can write P: Parser without naming the output. A trait parameter would only be needed if one type had to implement Parser for several output types.