Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 132 ยท Generics

Associated Types and Generic Traits

Understand Rust associated types vs generic trait parameters: Iterator::Item, default parameters like Add<Rhs=Self>, and stable GATs.

Traits can have blanks too. Sometimes a trait needs to mention a type that depends on the implementer: an iterator yields some kind of item, a container holds some kind of element, a + b produces some kind of output. Rust gives you two tools for this: associated types (type Item;) and generic parameters on the trait (trait From<T>). They look similar, but they answer different questions, and picking the right one is a design skill that shows up in every serious Rust API.

This lesson explains both, shows how to decide between them, introduces default type parameters such as the Rhs = Self in Add, and finishes with generic associated types (GATs), stable since Rust 1.65, which unlock "lending" iterators. You should be comfortable with traits, generics and trait bounds first.

Associated types

An associated type is a type placeholder declared inside a trait. Each implementation fills it in once. The most famous example is Iterator.

Rust
trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
    // ...many provided methods
}

Self::Item means "the Item type that this implementor chose". Implementing it for your own type is the classic way to learn how for loops work.

Rust Implementing Iterator with an associated type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You wrote one method and one type alias, and got sum, filter, map, zip and dozens more for free. Iterators explores that toolbox.

Using associated types in bounds

When you write a function over any iterator, you refer to the item type through the bound: I::Item, or by naming it in the trait bound, Iterator<Item = u32>.

Rust Constraining an associated type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Iterator<Item = u32> reads "any iterator whose item is u32". Writing it that way is only possible because Item is an associated type; if Item were a generic parameter you would have to write Iterator<u32> and the compiler would have to consider that one type can be an iterator of many item types.

A trait you design: a container

Here is a small trait of our own. Every container implementation has its own element type, and the function that uses the trait does not need to know it.

Rust Your own trait with an associated type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The function describe has one type parameter, C. If Container had been written as Container<Item>, the signature would need two parameters, fn describe<C: Container<I>, I>(...), and every function over containers would carry that extra type along. An associated type keeps signatures short because the item is determined by the container.

Associated type or generic parameter?

The difference comes down to one question: can a type implement the trait more than once?

  • Associated type: a type implements the trait at most once. Counter has exactly one Item. Choose this when the type is determined by the implementer.
  • Generic parameter: a type may implement the trait many times, once per parameter. String implements From<&str>, From<char> and From<Box<str>> at once. Choose this when one type can sensibly convert, compare or combine with several others.

You can see the first rule enforced by the compiler. Trying to implement Iterator twice for one type, with two different item types, is rejected.

Rust Two Item types for one type (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message is error[E0119]: conflicting implementations of trait \Iterator` for type `Digits``. If you did want several conversions, the trait must be generic, and the next example shows one that is.

Rust A generic trait with several implementations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Celsius implements ConvertTo<f64> and ConvertTo<String> at the same time. The call site has to say which one it wants, by an annotation on the variable or with ConvertTo::<String>::convert(&t). That need for annotation is the price of the flexibility, and a good reason not to use a generic parameter when an associated type would do.

Associated type Generic trait parameter
Implementations per type one many
Callers must name it no often yes
Example Iterator::Item, Deref::Target From<T>, Add<Rhs>, PartialEq<Rhs>
Syntax in bounds I: Iterator<Item = u8> T: From<u8>

Default type parameters: Add and Rhs = Self

A generic trait can give its parameter a default. Add is declared roughly like this:

Rust
trait Add<Rhs = Self> {
    type Output;

    fn add(self, rhs: Rhs) -> Self::Output;
}

That one declaration uses all the ideas in this lesson. Rhs is a generic parameter, because a type can be added to several things. It defaults to Self, so impl Add for Point means impl Add<Point> for Point. Output is an associated type, because for a given pair of operands the result type is fixed.

Rust Add with a different right-hand type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Use a default like this when one choice covers 90 percent of cases but you want to leave the door open. The same trick appears in HashMap<K, V, S = RandomState> and Vec<T, A = Global>. Operator overloading uses this family of traits throughout.

Associated constants and functions

A trait can also carry associated constants and associated functions (without self). They are part of the same family: things that belong to the implementing type.

Rust Associated consts and functions in a trait

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Here the type parameter S is chosen with the turbofish and there is no value yet: S::SIDES and S::unit() are resolved from the type alone. That is something trait objects cannot do, because a dyn Shape has no known type to ask.

Generic associated types (GATs)

An associated type can itself have parameters, usually a lifetime. This is called a generic associated type, stable since Rust 1.65. It solves a problem the ordinary Iterator cannot: returning items that borrow from the iterator itself.

Iterator::next(&mut self) -> Option<Self::Item> has one Item type for the whole life of the iterator, so an item can never borrow from &mut self; its lifetime would have to be named before next is even called. A "lending" iterator fixes that by making the item type depend on the lifetime of each next call.

Rust A lending iterator over mutable windows

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard slice::windows method gives you shared windows, and windows_mut does not exist in the standard library, precisely because a normal Iterator cannot hand out overlapping mutable borrows. With a GAT the borrow checker can see that each window ends before the next next() call begins. In daily code you will use GATs rarely: you meet them when designing streaming parsers, database cursors that reuse a buffer, and collection traits whose iterator type borrows the collection.

The where Self: 'a clause on the GAT is required in most cases. It states that the iterator must outlive the borrow, which makes the compiler accept the signature. The compiler suggests it when you leave it out, so you can follow its hint.

Common mistakes

  • Using a generic parameter where an associated type belongs. If a type can only ever have one value for the placeholder, make it associated; callers will not need to annotate anything.
  • Repeating Item in function signatures. Write impl Iterator<Item = T> rather than introducing an extra parameter.
  • Expecting the compiler to infer the output type from the left-hand side. Add::Output is chosen by the impl for the exact operand types, so Millimeters + Meters and Millimeters + Millimeters may differ.
  • Reaching for GATs too early. If the item does not borrow from the iterator itself, a plain Iterator is simpler and gets the entire adapter library.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is Item in trait Iterator { type Item; ... }?

    Item is an associated type: the implementation declares it once (type Item = u32;) and the rest of the trait refers to it as Self::Item.
  2. 2. When is a generic parameter on the trait (like From<T>) a better fit than an associated type?

    An associated type allows one implementation per type. A generic parameter lets String implement From<char>, From<&str> and more at once.
  3. 3. What does trait Add<Rhs = Self> mean?

    A default type parameter lets impl Add for Point mean impl Add<Point> for Point, while still permitting impl Add<Meters> for Millimeters.
  4. 4. Why can a normal Iterator not yield &mut windows that overlap?

    Item has no relation to the lifetime of each next call. A GAT such as type Item<'a> ties the item to that borrow.
  5. 5. What error do you get from writing impl Iterator for X twice with different Item types?

    A type can implement a trait without parameters only once. The compiler reports E0119: conflicting implementations of trait.

Summary

  • An associated type (type Item;) is a placeholder inside a trait that each implementation fills in exactly once.
  • Refer to it as Self::Item inside the trait, I::Item in bounds, or Iterator<Item = u32> to fix it.
  • Use an associated type when the implementer determines the type; use a generic trait parameter when one type needs many implementations.
  • Default parameters such as Add<Rhs = Self> keep the common case short while allowing other combinations; Add pairs a generic Rhs with an associated Output.
  • Traits can also have associated constants and functions, resolved from the type alone.
  • GATs (stable in Rust 1.65) give associated types their own parameters and enable lending iterators whose items borrow from the iterator.

Next: Const Generics