Sub topic 8
Associated types versus type parameters
This chapter assumes you can write a basic trait and implement it for a struct. It also assumes you know trait bounds on generic functions (T: Display) and have used Vec<T> and Option<T>. Here you learn the two ways a trait can mention another type, how to choose between them, and how to read the errors you get when you choose badly.
Two ways to name a related type
Some traits need to talk about a type other than the implementor. A container has an element type. A conversion has a target type. Rust gives you two tools for this:
- An associated type is a type placeholder declared inside the trait (
type Item;). Each implementation fills it in once. - A type parameter on the trait (
trait Convert<T>) makes the trait itself generic. A single type can then implementConvert<A>,Convert<B>, and so on.
The difference is how many implementations one type may have.
Associated types: one answer per implementor
Here is a trait whose element type is decided by the implementor:
use std::fmt::Debug;
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}
struct Stack {
items: Vec<i32>,
}
impl Container for Stack {
type Item = i32;
fn first(&self) -> Option<&i32> {
self.items.first()
}
}
fn print_first<C: Container>(c: &C)
where
C::Item: Debug,
{
println!("{:?}", c.first());
}
fn main() {
let s = Stack { items: vec![7, 8] };
print_first(&s);
}This prints Some(7). Three things to notice:
- Inside the trait,
Self::Itemnames the placeholder. Outside, you writeC::Item, or<C as Container>::Itemwhen the compiler needs the full form. print_firsthas one type parameter,C. The element type follows fromC, so the signature does not need a second parameter.- The bound
C::Item: Debugrestricts the associated type. It belongs in awhereclause, because it is a condition on a type reached throughC.
Because Stack can implement Container only once, Stack has exactly one Item. A second impl Container for Stack is rejected as conflicting, even with a different Item. This is the main property of associated types: the implementing type determines the associated type.
Type parameters: many implementations per type
If the same type should work with several partner types, make the trait generic:
trait Convert<T> {
fn convert(&self) -> T;
}
struct Meters(f64);
impl Convert<f64> for Meters {
fn convert(&self) -> f64 {
self.0
}
}
impl Convert<String> for Meters {
fn convert(&self) -> String {
format!("{} m", self.0)
}
}
fn main() {
let m = Meters(2.5);
let a: f64 = m.convert();
let b: String = m.convert();
let c = <Meters as Convert<String>>::convert(&m);
println!("{a} {b} {c}");
}This prints 2.5 2.5 m 2.5 m. Meters has two distinct implementations, Convert<f64> and Convert<String>. They are different traits as far as the compiler is concerned.
The price is that the compiler must work out which one you mean at each call. The annotated let bindings supply that information. Without them, m.convert(); fails with "type annotations needed". The last line shows the fully qualified syntax, which names the trait and its parameter explicitly.
The same decision seen at the call site
With a type parameter, callers often need annotations. With an associated type, they almost never do, because the implementor fixes the answer. This is why Iterator uses type Item. If it were Iterator<T>, every for loop and every .map(...) call would have to say which T it wants, even though a given iterator yields only one kind of item.
Using both in one trait
The two tools combine. The standard Mul trait takes a type parameter for the right-hand operand and an associated type for the result:
use std::ops::Mul;
#[derive(Debug, Clone, Copy)]
struct V2 {
x: i32,
y: i32,
}
impl Mul<i32> for V2 {
type Output = V2;
fn mul(self, k: i32) -> V2 {
V2 { x: self.x * k, y: self.y * k }
}
}
impl Mul<V2> for V2 {
type Output = i32;
fn mul(self, other: V2) -> i32 {
self.x * other.x + self.y * other.y
}
}
fn main() {
let a = V2 { x: 1, y: 2 };
let b = V2 { x: 3, y: 4 };
println!("{:?} {}", a * 2, a * b);
}This prints V2 { x: 2, y: 4 } 11. The right-hand side varies, so it is a type parameter. Once you pick Mul<i32> or Mul<V2>, the result type is determined, so it is an associated type. The reasoning is that anything the caller chooses is a parameter, and anything that follows from that choice is an associated type.
Mul is declared as trait Mul<Rhs = Self>. The = Self is a default type parameter. Writing impl Mul for V2 means impl Mul<V2> for V2. Defaults exist only on type parameters, not on associated types, in stable Rust.
Constraining associated types in bounds
Associated types appear in bounds in two forms:
use std::fmt::Debug;
fn sum_all<I: Iterator<Item = u32>>(iter: I) -> u32 {
iter.sum()
}
fn debug_join<I>(items: I) -> String
where
I: IntoIterator,
I::Item: Debug,
{
items
.into_iter()
.map(|x| format!("{x:?}"))
.collect::<Vec<_>>()
.join(",")
}
fn main() {
println!("{}", sum_all(vec![1u32, 2, 3].into_iter()));
println!("{}", debug_join(["a", "b"]));
println!("{}", debug_join(vec![1, 2, 3]));
}This prints 6, then "a","b", then 1,2,3.
Iterator<Item = u32>fixes the associated type to one concrete type. Use it when the function only works for that type.I::Item: Debugbounds the associated type by a trait. Use it when any item type with the capability is acceptable.
A common mistake is writing I: Iterator<Item: Debug> on an older compiler or mixing up the two forms. If you need an exact type, use =. If you need a capability, use a separate bound.
Comparing the two
| Question | Associated type | Trait type parameter |
|---|---|---|
| How many impls per implementing type? | One | Any number, one per argument |
| Who decides the related type? | The implementor | The caller or the inference |
| Call-site annotations | Rarely needed | Often needed |
| Signature noise in generic code | Low, one fewer parameter | Higher, every user lists the parameter |
| Default values | Not on stable | Supported (`Rhs = Self`) |
| Standard examples | `Iterator::Item`, `Deref::Target` | `From<T>`, `PartialEq<Rhs>`, `Add<Rhs>` |
Common errors
- Conflicting implementations. You wrote two
impl Container for Stackblocks with differentItemtypes. Associated types allow one. If you need both, the trait should be generic. - Type annotations needed. A generic trait is ambiguous at the call. Add a type to the
let, use the turbofish where the method has generics, or write<T as Trait<U>>::method(...). - Over-parameterizing. A trait such as
trait Container<Item>forces every function that takes a container to carry anItemparameter. Functions then needfn f<C: Container<I>, I>(c: &C), even thoughCalready determinesI. - Unconstrained type parameter in an impl. In
impl<T, U> Foo for Bar<T>, the parameterUis not tied to anything, and the compiler rejects it. An associated type avoids this because it is determined by the implementing type. - Forgetting to name the associated type.
Box<dyn Iterator>is incomplete. A trait object must specify its associated types, as inBox<dyn Iterator<Item = u32>>.
Rule of thumb
Start with an associated type. Switch to a type parameter only when you can name a real case where one type needs several implementations. From<T> is one: a type can be built from many sources. Iterator is the opposite: an iterator yields one kind of item.
Exercise
You are designing trait Parse with a method parse(s: &str) -> ???. A single type such as Config should be parseable from exactly one input format and always produce a ParseError type specific to it. Another trait, trait Encode, should let Config be encoded into JSON, TOML, and YAML as different target types. Which trait should use an associated type, and which should use a type parameter? Write the two trait declarations.
Show answer
Parse uses an associated type because each implementor has exactly one error type, chosen by the implementor: trait Parse: Sized { type Error; fn parse(s: &str) -> Result<Self, Self::Error>; }. Encode uses a type parameter because Config needs several implementations, one per target: trait Encode<Target> { fn encode(&self) -> Target; }, with impl Encode<Json> for Config, impl Encode<Toml> for Config, and so on. Callers of Encode pick the target by annotation, such as let j: Json = cfg.encode();.