liveBook · Manning

Associated type

As explained in Learn Rust in a Month of Lunches

An associated type is a type declaration attached to a Rust trait whose concrete value is specified for each implementation.

An associated type is a type declaration attached to a Rust trait. Each implementation chooses the concrete type that goes with that trait. In an implementation, write the chosen type with `type`, then refer to it through the trait’s methods. section 8.4 section 20.5.2

A few standard-library traits make the pattern easier to recognize:

  • `Iterator` declares the associated type `Item`; an iterator implementation can set `type Item = String`, so `.next()` returns `Option<String>`. section 8.2
  • `Future` declares `type Output`; an asynchronous function returning `u8` is represented as `impl Future<Output = u8>`. section 19.3.1
  • `Add` declares `type Output`; adding two integers produces the associated output type selected by its implementation. section 20.5.2

Choosing the associated type

A custom `ChangeForm` trait can require a value to transform into another form: `trait ChangeForm { type SomethingElse; fn change_form(self) -> Self::SomethingElse; }`. Its `String` implementation chooses `char`, while its `i32` implementation chooses `i64`. The method’s return type follows that choice, so calling `change_form()` on a string yields a character and calling it on an integer yields an integer with the selected wider type. section 20.5.2

pub trait Add<Rhs = Self> {
    type Output;
 
    fn add(self, rhs: Rhs) -> Self::Output;    #1
}

Read the `Add` trait signature to see an associated `Output` type flow directly into the `add` method’s return type. section 20.5.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines the syntax and works through custom and standard traits, but defers deeper details of pinning and asynchronous internals.
Examples
Demonstrates Iterator::Item, Future::Output, Add::Output, and a ChangeForm trait implemented for String and i32.
What it assumes
Assumes basic Rust traits and implementations while explaining associated-type terminology through small examples.
What you can do after
Apply associated types by declaring them in traits and choosing concrete types when implementing those traits.
How it connects
Connects associated types with traits, iterators, futures, async functions, and the Add trait.

Also explained in

Compare how 2 books explain associated type →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.