In Rust, why does the `Iterator` trait declare `type Item` instead of being generic as `Iterator<T>`, and when is a type parameter the better choice?
answer
- how many impls per type
- who chooses the type
- inference at the call site
- E0283: type annotations needed
- inputs as parameters, outputs associated
basics
~20 sWith an associated type, a type implements the trait at most once and the implementer fixes Item, so callers never annotate it. A type parameter allows one impl per argument type, which suits inputs such as Add's Rhs.
solid answer
~50 sA trait with a type parameter, `Iterator<T>`, is really a family of traits: one type could implement `Iterator<u32>` and `Iterator<String>` side by side, so every call to `next` would have to say which one, and rustc stops with E0283 (`type annotations needed`) when it cannot tell. An associated type, `type Item;`, is chosen by the implementer, and a type can have only one impl of the trait, so `Item` is a function of the implementing type and is always inferred. Bounds get shorter too: `I: Iterator<Item = u32>` instead of carrying an extra `T` through every signature. Use a type parameter when one type genuinely needs several impls, which is typical for *inputs*: `i32` implements both `Add<i32>` and `Add<&i32>`, and `String` implements `Add<&str>`. `Add` shows the usual split: the input `Rhs` is a parameter, the result `Output` is associated.
code
rust · 24 lines// Associated type: one Output per implementing type, inferred at the call site.
trait Parser {
type Output;
fn parse(&self, input: &str) -> Option<Self::Output>;
}
struct PortParser;
impl Parser for PortParser {
type Output = u16;
fn parse(&self, input: &str) -> Option<u16> {
input.trim().parse().ok()
}
}
fn parse_all<P: Parser>(p: &P, lines: &[&str]) -> Vec<P::Output> {
lines.iter().filter_map(|l| p.parse(l)).collect()
}
fn main() {
let port = PortParser.parse("8080"); // no annotation: Output is fixed to u16
let ports = parse_all(&PortParser, &["80", "x", "443"]);
println!("{port:?} {ports:?}");
}go deeper
Recall that Iterator declares type Item and that an impl writes type Item = u32. Be able to read Self::Item in a signature and say it means the implementer's chosen type.
Explain the impl-count difference: a type parameter permits one impl per argument, an associated type permits one impl in total, which is why calls infer Item and generic traits hit E0283.
Choose the shape when designing a trait: parameters for inputs a type may accept several of, associated types for results it determines, and know the stable limits such as no associated type defaults.
Treat the choice as public API: switching between a parameter and an associated type later breaks every implementer and most bounds that name the trait, so settle it before a trait leaves the crate.
## Two ways to put a type into a trait A Rust trait can mention a type it does not know yet in two ways: - A **generic type parameter** on the trait itself: `trait Parse<Out> { fn parse(&self, input: &str) -> Option<Out>; }`. Whoever *uses* the trait names `Out`. - An **associated type** declared inside it: `trait Parser { type Output; fn parse(&self, input: &str) -> Option<Self::Output>; }`. Whoever *implements* the trait names `Output`, once, in the impl block (`type Output = u16;`). The Rust Reference calls an associated type a type alias associated with another type: for a type `X`, `<X as Parser>::Output` is an alias of whatever the impl wrote. The standard library's `Iterator` is the textbook case: it declares `type Item;` and `fn next(&mut self) -> Option<Self::Item>`. ## What the generic version would cost The decisive difference is **how many impls one type may have**. `Parse<u16>` and `Parse<i64>` are different traits as far as coherence is concerned, so one parser type may implement both. That is sometimes the point, but it means a call site has to pick one: ```rust let a = NumParser.parse("8080"); // two impls match ``` rustc 1.99 rejects this with **E0283**, `type annotations needed for Option<_>`, and notes that multiple impls satisfy `NumParser: Parse<_>`. Every caller must now write `let a: Option<u16> = ...` or `Parse::<u16>::parse(&NumParser, ...)`. The Rust Book makes the same argument about a hypothetical `Iterator<T>`: you would have to annotate which iterator implementation you mean wherever you call `next`. Generics also leak into every signature that mentions the trait. A function over any parser would read `fn parse_all<P: Parse<O>, O>(p: &P, ...) -> Vec<O>`, with an extra parameter `O` that callers and readers must track. ## What the associated version buys With `type Output;`, a type can implement `Parser` **at most once**; a second `impl Parser for NumParser` with a different `Output` is rejected as a conflicting implementation (E0119). In exchange: 1. **Inference always works.** Once the compiler knows the implementing type, it knows `Output`. `PortParser.parse("8080")` is an `Option<u16>` with no annotation. 2. **Signatures stay short.** `fn parse_all<P: Parser>(p: &P, lines: &[&str]) -> Vec<P::Output>` needs one parameter, not two. 3. **Bounds can pin or constrain it.** `P: Parser<Output = u16>` fixes the type; `where P::Output: Display` only requires a capability. 4. **It documents the contract.** Implementers must supply the type, and rustdoc lists it with the impl. ## When a type parameter is the right choice Pick by asking: *could one implementing type sensibly provide this trait more than once, varying this type?* | Trait in std | Shape | Why | |---|---|---| | `Iterator` | `type Item` | a given iterator yields one kind of item | | `Deref` | `type Target` | a smart pointer dereferences to one type | | `FromStr` | `type Err` | parsing a type fails in one error type | | `From<T>` | parameter `T` | `String` converts from `&str`, `char`, `Box<str>` and more | | `Add<Rhs = Self>` | parameter `Rhs`, `type Output` | `i32 + i32` and `i32 + &i32` both exist; each has one result | | `Sum<A = Self>` | parameter `A` | `u32` can be summed from `u32` items and from `&u32` items | The recurring pattern is **inputs as parameters, outputs as associated types**. An operator's right-hand side varies, so `Add` takes `Rhs`; the result is determined by the operand types, so `Output` is associated. Type parameters can also carry defaults (`Rhs = Self`), which is why `impl Add for Point` needs no angle brackets. ## Rules that trip people up - **No defaults for associated types on stable.** Writing `type Output = String;` inside the trait is rejected with E0658, `associated type defaults are unstable`. Every impl must name the type, and leaving it out is E0046 (`not all trait items implemented`). - **Associated types are compile-time aliases.** Nothing is looked up at run time; `P::Output` is replaced by the concrete type when the generic code is monomorphised. - **A plain associated type does not stop `dyn`.** `Box<dyn Iterator<Item = u32>>` is fine as long as the `Item` is specified; among associated items, it is associated consts and associated types with their own generic parameters that rule `dyn` out (generic methods are a separate rule). - **If you need several outputs per type, say so.** Either keep a type parameter, or give each output its own small type that implements the associated-type trait once.
- Could a Rust type implement a trait with an associated `Output` twice, once per output type?No. Coherence allows one impl of a trait per type, and the associated type is part of that single impl, so a second `impl Parser for NumParser` is rejected with E0119 (conflicting implementations). If one type really needs several outputs, the trait should take a type parameter, or each output should get its own parser type.
- Can a Rust trait give an associated type a default, the way `Add<Rhs = Self>` defaults its parameter?Not on stable. `type Output = String;` inside a trait is rejected with E0658, `associated type defaults are unstable`, so every impl must write its own `type Output = ...;`. Defaults are a stable feature of type parameters only, which is how `impl Add for Point` can omit `Rhs`.
- Why does `std::ops::Add` use both a type parameter and an associated type?The right-hand operand varies: `i32` implements `Add<i32>` and `Add<&i32>`, and `String` implements `Add<&str>`, so `Rhs` must be a parameter to allow several impls. For each operand pair the result is fixed, so `Output` is associated and `a + b` never needs an annotation.
- Associated types and trait type parameters are two spellings of the same thing.
- One type can implement Iterator twice if the two Item types differ.
- With an associated type, the caller picks Item at each call site.
- Any associated type makes a trait unusable as dyn Trait.
- Associated types are resolved at run time through the vtable.
- A trait can default an associated type on stable, like type Output = String.