Rust Abstractions · 18 min · free with an account

Associated Types

Lesson preview · about 30%

An associated type fixes one output type per implementation.

Core idea

Associated type: one impl per type. Generic parameter: many impls per type.

Start with the idea

A generic parameter lets a type implement a trait many times; an associated type lets it implement it once with a chosen output. Iterator uses Item this way, which is why you write Iterator<Item = u32> rather than passing the element type at every call site.

An associated type is a type chosen by a particular implementation of a trait. Iterator::Item is the classic example: once a type implements Iterator, its Item is fixed for that implementation. A caller can write a bound such as I: Iterator<Item = u32> to say exactly which stream it accepts. This is different from giving the trait a type parameter that might allow the same implementer to implement several versions.

In the Container example, Bag chooses String for Item. The get method then returns Option<&String>, borrowing an element from the bag rather than copying it.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Ownership Mastery