Sub topic 5
Associated type or generic parameter?
This chapter assumes you can write and implement traits, use generic bounds such as T: Display, and have seen Iterator with its Item type. You do not need lifetimes beyond the basics.
A trait can let each implementer choose a type in two ways. It can take a generic parameter, as in trait Convert<T>. Or it can declare an associated type, as in trait Iterator { type Item; }. The two look similar, but they make different promises, and picking the wrong one leads to awkward signatures or impossible designs.
The core question: how many choices per type?
Ask this about the type you want to leave open: can one implementing type reasonably have several different values for it?
- If yes, use a generic parameter. The trait is really a family of traits,
Convert<f64>,Convert<String>and so on, and a type can implement as many members of the family as it likes. - If no, use an associated type. Once the compiler knows
Self, it knows the associated type. A type can implement the trait only once.
A generic parameter is an input to the trait. An associated type is an output, determined by the inputs. For Iterator, the input is Self (the iterator), and the output is Item.
A trait with a generic parameter
This trait converts a value into some target type chosen by the caller. A single type can convert into many targets, so the target is a parameter.
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 number: f64 = m.convert();
let text: String = m.convert();
println!("{} and {}", number, text);
}This prints 2.5 and 2.5 m. Both impl blocks are legal because Convert<f64> and Convert<String> are different traits as far as the compiler is concerned.
The call sites need type annotations. Writing let x = m.convert(); fails with "type annotations needed" (error E0283), because Meters implements several Convert<_> traits and nothing says which one you mean. Here the annotations are the point: the caller picks the conversion.
The same idea as an associated type
Now suppose the trait said type Target; instead. Then a second impl Convert for Meters would be rejected with a conflicting implementations error (E0119). The trait would be implemented once per type, so Meters could convert to only one thing. Sometimes that is exactly what you want. Iterator works this way: a given iterator yields one kind of item, and nobody needs to ask which Iterator impl of Countdown they are calling.
| Property | Generic parameter `Trait<T>` | Associated type `type T;` |
|---|---|---|
| Implementations per type | Many, one per `T` | One |
| Who picks the type | The caller, or the compiler by inference | The implementer |
| Call-site annotations | Often needed | Rarely needed |
| Bounds in generic code | Extra parameter on every function | Written as `T::Name` or `Trait<Name = X>` |
| Named in a trait object | `dyn Trait<f64>` | `dyn Trait<Name = f64>` |
Why associated types keep signatures short
Consider a trait for graphs. Each graph type has a single node type, so the node type is determined by the graph. Compare two designs of the same trait, one with an associated type and one with a parameter.
use std::fmt::Debug;
trait Graph {
type Node: Copy + Debug;
fn edges(&self) -> Vec<(Self::Node, Self::Node)>;
}
trait GraphOf<N> {
fn edges_of(&self) -> Vec<(N, N)>;
}
struct Ring {
size: u32,
}
impl Graph for Ring {
type Node = u32;
fn edges(&self) -> Vec<(u32, u32)> {
(0..self.size).map(|i| (i, (i + 1) % self.size)).collect()
}
}
impl GraphOf<u32> for Ring {
fn edges_of(&self) -> Vec<(u32, u32)> {
self.edges()
}
}
fn print_assoc<G: Graph>(g: &G) {
for (a, b) in g.edges() {
println!("{:?} -> {:?}", a, b);
}
}
fn print_param<N: Debug, G: GraphOf<N>>(g: &G) {
for (a, b) in g.edges_of() {
println!("{:?} -> {:?}", a, b);
}
}
fn main() {
let ring = Ring { size: 3 };
print_assoc(&ring);
print_param::<u32, _>(&ring);
}The program prints the three edges 0 -> 1, 1 -> 2, 2 -> 0 twice.
print_assoc has one type parameter. print_param needs two, N and G, even though N carries no information that G does not already imply. Every function, struct, and impl that mentions the graph must repeat N, and the repetition spreads through the whole codebase. This is the main practical reason to prefer an associated type when the type is functionally determined by Self.
The parameter version can also be ambiguous. If Ring implemented GraphOf<u32> and GraphOf<u64>, print_param(&ring) would need a turbofish or an annotation.
Using both in one trait
Many traits need both kinds. std::ops::Add is the standard example:
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}The right-hand side is a parameter, because one type can be added to several different things. The result type is associated, because once you know the left and right types, the result is fixed. Here is a type that implements Add twice:
use std::ops::Add;
#[derive(Debug, Clone, Copy)]
struct Vec2 {
x: i32,
y: i32,
}
impl Add for Vec2 {
type Output = Vec2;
fn add(self, other: Vec2) -> Vec2 {
Vec2 { x: self.x + other.x, y: self.y + other.y }
}
}
impl Add<i32> for Vec2 {
type Output = Vec2;
fn add(self, k: i32) -> Vec2 {
Vec2 { x: self.x + k, y: self.y + k }
}
}
fn main() {
let v = Vec2 { x: 1, y: 2 };
println!("{:?} {:?}", v + v, v + 10);
}This prints Vec2 { x: 2, y: 4 } Vec2 { x: 11, y: 12 }. Add<Vec2> and Add<i32> are two separate impls, which only works because Rhs is a parameter. Each impl then fixes its own Output.
A rule that follows from this: put a type in the parameter list when it is an input that varies, and in an associated type when it is a result that follows from the inputs.
Decision flow
Edge cases and gotchas
- Several items for one collection.
Vec<T>seems to want to iterate by value, by reference, and by mutable reference. BecauseItemis associated,Vec<T>cannot implementIteratorthree times. The standard library avoids this by implementingIntoIteratorfor three differentSelftypes:Vec<T>,&Vec<T>, and&mut Vec<T>. Each has its ownItem. When you need several outputs for one type, use a differentSelf(a reference or a newtype wrapper) or separate methods such asiter()anditer_mut(). - Blanket impls and overlap. Coherence rules see
impl<T> Trait<T> for Xandimpl Trait<u8> for Xas overlapping. Associated types can make overlap checks stricter or looser depending on the bounds, so keep blanket impls narrow. - Defaults. A generic parameter can have a default, as
Rhs = Selfshows. Defaults for associated types are not stable, so you cannot writetype Output = Self;inside a trait declaration on stable Rust. - Trait objects. With an associated type, a
dyntype must name it, as indyn Iterator<Item = u32>. With a parameter, you supply it positionally, as indyn Convert<f64>. The next chapters cover trait objects in more detail. - Changing your mind is a breaking change. Switching a published trait between the two forms changes every impl and every bound. Decide before release.
Summary of the heuristic
- List the types the trait leaves open.
- For each one, ask whether one implementing type could meaningfully use two different values.
- Types that can vary independently become generic parameters.
- Types that follow from
Selfand the parameters become associated types. - If you cannot tell, start with an associated type when the trait represents a single capability of its implementer, such as "this is a stream of X". Prefer a parameter when it represents a relationship between two types, such as "this can become Y".
Exercise
You are designing trait Parse with a method fn parse(text: &str) -> Self::Output. Should Output be an associated type or a generic parameter on Parse<T>, if the goal is to let the type Config be parsed both into a Config value and into a Vec<String> of its keys? Explain your choice.
Show answer
A generic parameter. Config needs to implement the trait twice with different target types, Parse<Config> and Parse<Vec<String>>, which an associated type forbids (conflicting implementations, E0119). The cost is that callers need annotations such as let keys: Vec<String> = Config::parse(text);. If Config only ever had one parse result, an associated type would give simpler signatures.
Exercise
Add has both Rhs and Output. Why is Output not a third generic parameter written Add<Rhs, Out>?
Show answer
For a given Self and Rhs, there is exactly one result type, so Output is determined by the other types. Making it a parameter would force every bound to name it (T: Add<T, T>), allow multiple impls differing only in Out, and produce ambiguous inference. As an associated type it can be constrained only when needed, as in T: Add<Output = T>.