Sub topic 9
Generic associated type syntax
This chapter assumes you can write a trait with a plain associated type (type Item;), read where clauses, and use lifetime annotations such as &'a self. It covers the syntax only. The next chapters use it for lending iterators and type families.
From associated type to generic associated type
A plain associated type has one fixed meaning per implementation. A generic associated type (GAT) is an associated type that takes its own parameters, so it works like a type-level function. GATs were stabilized in Rust 1.65.
You write the parameters in angle brackets after the name, the same way you write them on a struct:
| Form | Meaning |
|---|---|
| `type Item;` | Plain associated type |
| `type Item<'a>;` | Takes a lifetime parameter |
| `type Pointer<T>;` | Takes a type parameter |
| `type Iter<'a>: Iterator<Item = &'a i32>;` | Parameter plus a bound on the result |
| `type Item<'a> where Self: 'a;` | Parameter plus a `where` clause |
You can also combine lifetime and type parameters, as in type Slot<'a, T>.
A complete example
This trait promises an iterator type whose lifetime depends on how long the container is borrowed:
trait Container {
type Iter<'a>: Iterator<Item = &'a i32>
where
Self: 'a;
fn iter<'a>(&'a self) -> Self::Iter<'a>;
}
struct Numbers(Vec<i32>);
impl Container for Numbers {
type Iter<'a> = std::slice::Iter<'a, i32>
where
Self: 'a;
fn iter<'a>(&'a self) -> Self::Iter<'a> {
self.0.iter()
}
}
fn main() {
let n = Numbers(vec![1, 2, 3]);
let total: i32 = n.iter().sum();
println!("{}", total);
}The program prints 6.
The three places the syntax appears
flowchart TDReplace that sketch with the real diagram below.
- Declaration. The trait lists the parameters, then optional bounds after a colon, then an optional
whereclause. Thewhereclause goes after the bounds and before the semicolon. - Implementation. The impl repeats the parameter list and assigns a type with
=. Anywhereclause goes after the assigned type. The parameters can appear in the assigned type, as'adoes inslice::Iter<'a, i32>. - Use. Every mention of the GAT must supply arguments:
Self::Iter<'a>, never bareSelf::Iter. Outside the trait you write<T as Container>::Iter<'a>.
Bounds on the result and on the parameters
A bound after the colon applies to the type the impl chooses. Here Iterator<Item = &'a i32> forces every implementation to produce an iterator over &'a i32. Generic code can then rely on it without knowing the concrete type.
A where clause applies to the parameters or to Self. The clause where Self: 'a says the implementing type must live at least as long as 'a. The compiler requires it in this example because the trait's method signature uses &'a self. Chapter "Why GATs need where Self: 'a" explains the reason.
Common errors
- Writing
Self::Iterwithout arguments gives an error about missing generics. - Putting the
whereclause before the=in an impl is a mistake. In impls it goes after the assigned type. - Using the GAT with a
'athat is not in scope gives "use of undeclared lifetime name". Declare<'a>on the method.
Exercise
Given trait Family { type Wrapped<T>; }, write the impl line for a type OptionFamily that makes Wrapped<T> mean Option<T>, and write the type you would use for a wrapped String.
Show answer
Inside impl Family for OptionFamily, write type Wrapped<T> = Option<T>;. A wrapped String is <OptionFamily as Family>::Wrapped<String>, which equals Option<String>.