Sub topic 11
Associated Types
This chapter assumes you can declare and implement a trait, write a generic function with a trait bound, and read Option<&T> signatures. Generic type parameters (<T>) should already feel familiar. Here you will learn the other way a trait can mention a type: a type that each implementor chooses once.
The problem: a trait that talks about another type
Suppose you want a trait for collections that can return their first element. The return type depends on what the collection holds. A Vec<i32> returns an i32, and a Vec<String> returns a String.
The trait can't name that type directly, so it declares a placeholder inside itself. That placeholder is an associated type. Each impl block fills it in.
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]);
}The program prints Some(10). Four details matter:
type Item;declares the placeholder in the trait. Inside the trait,Self::Itemrefers to it.type Item = T;in the impl block chooses the concrete type. Every impl must provide every associated type, or the compiler reports error E0046.print_headhas one type parameter,C. It doesn't need a second parameter for the element type, becauseC::Itemis derived fromC.C::Item: Debugis a bound on the associated type. Without it,{:?}fails to compile because the compiler knows nothing aboutC::Item.
Reading and writing associated type paths
C::Item is shorthand. The full form is <C as Container>::Item, which means "the Item type from C's implementation of Container". The short form works when only one bound on C has an Item. If C is bounded by two traits that both declare Item, the short form is ambiguous and you must write the full form.
You can also use the full form outside generic code:
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 sum_head<C>(c: &C) -> i32
where
C: Container<Item = i32>,
{
c.head().copied().unwrap_or(0)
}
fn main() {
let x: <Vec<i32> as Container>::Item = 5;
println!("{}", x);
println!("{}", sum_head(&vec![7, 8]));
println!("{}", sum_head(&Vec::<i32>::new()));
}The output is 5, 7, and 0.
Container<Item = i32> is an equality constraint. It accepts only containers whose Item is exactly i32, so sum_head(&vec!["a"]) is rejected at compile time. Use this form when you need to pin the associated type to a specific type, rather than just require a trait on it.
The standard library's main example: Iterator
You have already used an associated type, because Iterator is declared roughly like this:
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// many provided methods: map, filter, sum, ...
}To make your own type iterable, you set Item and write next. Every provided method then works for free.
struct Countdown {
remaining: u32,
}
impl Iterator for Countdown {
type Item = u32;
fn next(&mut self) -> Option<u32> {
if self.remaining == 0 {
None
} else {
self.remaining -= 1;
Some(self.remaining + 1)
}
}
}
fn main() {
for n in (Countdown { remaining: 3 }) {
println!("{n}");
}
let total: u32 = Countdown { remaining: 4 }.sum();
println!("total = {total}");
}This prints 3, 2, 1, then total = 10. The for loop and sum need no extra information about the element type. Countdown is an iterator over u32, and that is the only possible reading.
Generic code over iterators uses the same pattern as print_head:
fn first_or_default<I>(mut iter: I) -> I::Item
where
I: Iterator,
I::Item: Default,
{
iter.next().unwrap_or_default()
}
fn main() {
println!("{}", first_or_default(vec![5, 6].into_iter()));
println!("{}", first_or_default(Vec::<i32>::new().into_iter()));
}The return type I::Item appears in the signature even though I::Item is not a parameter. The compiler computes it from I. The output is 5 and 0.
Associated type or generic parameter?
A trait can also take a type parameter, like trait Convert<T>. The two designs behave differently, and the difference is how many implementations one type may have.
trait Convert<T> {
fn convert(&self) -> T;
}
struct Celsius(f64);
impl Convert<f64> for Celsius {
fn convert(&self) -> f64 {
self.0
}
}
impl Convert<String> for Celsius {
fn convert(&self) -> String {
format!("{}C", self.0)
}
}
fn main() {
let c = Celsius(21.5);
let n: f64 = c.convert();
let s: String = c.convert();
println!("{n} {s}");
}This prints 21.5 21.5C. Celsius implements Convert twice, once for each T. The call site picks one through the annotated variable type.
If Convert used an associated type Output instead, the second impl would be rejected as a conflicting implementation (E0119). A type can implement a trait only once, so it can only choose one Output.
| Row | Associated type | Generic parameter |
|---|---|---|
| Impls per type | One | Many, one per parameter value |
| Who picks the type | The implementor | The caller, or inference |
| Bound syntax | `C: Container` | `C: Convert<f64>` |
| Extra parameters in generic signatures | None | One more per trait use |
| Typical use | `Iterator`, `Deref`, `Add::Output` | `From<T>`, `PartialEq<Rhs>` |
The rule of thumb: if, for a given implementing type, there is logically one answer, use an associated type. A Countdown yields u32 and nothing else. If one type can sensibly relate to several others, as String: From<&str> and String: From<char> do, use a parameter.
Associated types in std bounds
Several standard traits use associated types, and you meet them in bounds constantly. Add is a common case, since its result type is Add::Output:
use std::ops::Add;
fn double<T>(x: T) -> T
where
T: Add<Output = T> + Copy,
{
x + x
}
fn main() {
println!("{}", double(21));
println!("{}", double(1.25));
}This prints 42 and 2.5. Without Output = T, the compiler would only know that x + x produces some T::Output, and it couldn't return that value as a T. The Rhs parameter of Add is a type parameter with a default, and the next-but-one chapters cover defaults.
Common errors
- Missing bound on the associated type. Writing
C: Containerand then printingC::Itemwith{:?}fails because nothing saysC::Item: Debug. AddC::Item: Debugto thewhereclause. - Forgetting an associated type in an impl. Every
type X;in a trait needs a matchingtype X = ...;in each impl, unless the trait provides a default (which is unstable in current Rust). - Ambiguous associated type. With
T: Iterator + Container, writingT::Itemis ambiguous. Use<T as Iterator>::Itemor<T as Container>::Item. - Trying to implement the trait twice for one type. Two
impl Container for MyTypeblocks with differentItemtypes conflict. Switch to a trait parameter if you really need both. - Using
Item = Xon a trait with no such associated type.T: Container<Elem = i32>fails because the name must match the declared one. - Over-constraining with equality.
I: Iterator<Item = i32>rejects an iterator over&i32. Often a looser bound such asI::Item: Copy + Add<Output = I::Item>makes the function more reusable.
Associated types and trait objects
A trait object must name all its associated types, because the compiler has to know the layout of the values it handles. Box<dyn Iterator<Item = u32>> is valid, and Box<dyn Iterator> is not. This is another reason Item = ... syntax shows up in so many signatures.
Exercise
A trait Parse is meant to turn a &str into a value, and a single type such as Config should only ever parse into one output type, Config::Output. Should Output be an associated type or a type parameter of Parse? What changes if you later want Config to parse into both Settings and Summary?
Show answer
Use an associated type: trait Parse { type Output; fn parse(s: &str) -> Self::Output; }. This fits because there is exactly one answer per implementing type, and callers write only T: Parse. If Config must parse into both Settings and Summary, the associated type forbids a second impl (E0119). Change the design to trait Parse<Out> so Config can implement Parse<Settings> and Parse<Summary>, and callers choose through annotations.
Exercise
This function fails to compile with "<I as Iterator>::Item doesn't implement std::fmt::Display". What single change fixes it?
fn show_all<I: Iterator>(iter: I) {
for x in iter {
println!("{x}");
}
}
Show answer
Add a bound on the associated type, for example fn show_all<I>(iter: I) where I: Iterator, I::Item: std::fmt::Display. The bound I: Iterator says nothing about what Item can do, so each capability the body needs must be required explicitly.