Sub topic 9
Generic associated type syntax
This chapter covers the syntax of generic associated types (GATs). It assumes you can write a trait with a plain associated type such as type Item;. It also assumes you know basic lifetime annotations and generic bounds. GATs were stabilized in Rust 1.65, so any current toolchain accepts the code below.
What a GAT adds
A plain associated type is a single type that each implementer picks once. A generic associated type is a type constructor. It takes parameters, and the implementer decides what type results from each choice of arguments.
The extra parameters go on the associated type itself, in angle brackets, like the parameters of a generic struct:
trait Example {
type Plain; // one type per implementer
type WithLifetime<'a>; // one type per lifetime 'a
type WithType<T>; // one type per type T
}Three kinds of parameter are allowed: lifetimes, types, and const generics. Lifetime and type parameters cover nearly all real uses, so this chapter focuses on those.
Because Self::WithLifetime is not a type until you supply 'a, you must always write the arguments. Writing Self::WithLifetime alone is an error.
Anatomy of a declaration
A GAT declaration in a trait has up to four parts, in this order:
- The keyword
typeand the name. - The parameter list, such as
<'a>or<T>. - Optional bounds on the resulting type, after a colon.
- An optional
whereclause, before the semicolon.
trait Lender {
type Item<'a>: std::fmt::Debug
where
Self: 'a;
fn lend<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}Here Item<'a> is the name with its parameter. : std::fmt::Debug promises that every Item<'a> is Debug. where Self: 'a says the implementing type must live at least as long as 'a. The next chapter explains why that clause is required. For now, treat it as mandatory whenever a lifetime parameter appears in a method that borrows self.
The trait method uses the GAT as Self::Item<'a>. The lifetime 'a is the same one that appears in &'a mut self. That link is the point of a GAT: the returned type depends on how long self is borrowed.
Implementing a GAT
An implementation assigns a type to the GAT with =. The parameter names are declared again on the left, and the where clause goes after the assigned type.
trait Lender {
type Item<'a>
where
Self: 'a;
fn lend<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
struct Chunks {
data: Vec<u8>,
pos: usize,
size: usize,
}
impl Lender for Chunks {
type Item<'a> = &'a [u8] where Self: 'a;
fn lend<'a>(&'a mut self) -> Option<Self::Item<'a>> {
if self.pos >= self.data.len() {
return None;
}
let end = (self.pos + self.size).min(self.data.len());
let chunk = &self.data[self.pos..end];
self.pos = end;
Some(chunk)
}
}
fn count<L: Lender>(mut lender: L) -> usize {
let mut n = 0;
while let Some(_) = lender.lend() {
n += 1;
}
n
}
fn main() {
let mut chunks = Chunks { data: vec![1, 2, 3, 4, 5], pos: 0, size: 2 };
while let Some(chunk) = chunks.lend() {
println!("{:?}", chunk);
}
let again = Chunks { data: vec![9; 7], pos: 0, size: 3 };
println!("{}", count(again));
}This prints [1, 2], [3, 4], [5] and then 3. For Chunks, Item<'a> is &'a [u8], a slice borrowed from the struct for as long as the lend call's borrow lasts. A plain associated type could not say this, because it has no way to mention 'a.
Two details are worth noting:
- The parameter name on the impl side does not have to match the trait's.
type Item<'b> = &'b [u8]would also work. Using the same name is a convention. - The signature of
lendin the impl may useSelf::Item<'a>or the concreteOption<&'a [u8]>. The compiler treats them as equal.
Lifetime elision with GATs
Method signatures can use the anonymous lifetime, so you often do not need to name 'a:
trait Lender {
type Item<'a>
where
Self: 'a;
fn lend(&mut self) -> Option<Self::Item<'_>>;
}Elision gives '_ the lifetime of the &mut self borrow, which is the same signature as before. In generic code you will mostly see the explicit form when a bound has to name the lifetime, and the elided form in simple methods.
GATs with type parameters
A GAT can take a type parameter instead of a lifetime. Such a trait describes a family of types, one for each T. The bounds you put on T go in the where clause, as in this example:
trait Family {
type Of<T>: Clone
where
T: Clone;
fn wrap<T: Clone>(value: T) -> Self::Of<T>;
}
struct VecFamily;
impl Family for VecFamily {
type Of<T> = Vec<T> where T: Clone;
fn wrap<T: Clone>(value: T) -> Vec<T> {
vec![value]
}
}
fn main() {
let v = VecFamily::wrap(3);
let w = v.clone();
println!("{:?} {:?}", v, w);
}This prints [3] [3]. Notice that the promise Of<T>: Clone is only valid because the where T: Clone clause is present. Vec<T> is Clone only when T is. The trait and the impl both state the same condition, and the compiler checks that the impl's clause is no stricter than the trait's.
The previous chapter's pattern also works with Rc and Box. The type parameter plays the same role as T in Vec<T>: the implementer decides what Of<T> expands to.
Where to put bounds and clauses
The same rules apply wherever a GAT appears. The table shows each form and where it is used.
| Form | Where | Meaning |
|---|---|---|
| `type Item<'a>;` | trait | Declares a GAT with a lifetime parameter |
| `type Item<'a>: Debug;` | trait | Every `Item<'a>` must implement `Debug` |
| `type Item<'a> where Self: 'a;` | trait | Requires the implementer to outlive `'a` |
| `type Item<'a> = &'a [u8] where Self: 'a;` | impl | Assigns a concrete type; the clause follows the type |
| `Self::Item<'a>` | method signature | Uses the GAT with a specific lifetime |
| `L::Item<'a>` | generic function | Uses the GAT of a type parameter `L` |
| `<L as Lender>::Item<'a>` | anywhere | Fully qualified form, useful when names are ambiguous |
The where clause belongs after the assigned type in an impl. An older placement before the = still compiles but triggers a future-compatibility warning, so avoid it in new code.
The fully qualified form works the same way as for plain associated types. The arguments go after the name: <Chunks as Lender>::Item<'static> names the slice type for a 'static borrow, which is &'static [u8] here.
How the pieces fit together
The diagram follows one GAT from declaration to use.
Common errors
Missing arguments. Writing Option<Self::Item> in a method when Item is a GAT gives an error like "missing generics for associated type Lender::Item". The fix is to supply every parameter: Self::Item<'a> or Self::Item<'_>.
Missing where Self: 'a. If a trait declares type Item<'a>; and a method uses Self::Item<'a> with &'a mut self, the compiler reports "missing required bound on Item". It suggests adding where Self: 'a. Add it to the trait and to every impl.
Wrong parameter kinds. The arguments at a use site must match the declaration. Passing a type where a lifetime is expected, as in Self::Item<u32> for type Item<'a>, is an error.
Mismatched impl clause. An impl cannot add a where clause that the trait did not declare, because callers would not know it. Moving a bound into the trait fixes this.
Expecting Iterator to work. Implementing Iterator for a lending type does not compile, because Iterator::Item has no lifetime parameter. A lending trait needs its own definition, as above, and it cannot be used in a for loop. You must write while let as shown.
Summary of rules
- Parameters go after the GAT's name, in both the trait and the impl.
- Every use must supply every argument, directly or through
'_. whereclauses follow the declaration in a trait and follow the assigned type in an impl.- A lifetime GAT used in a method that borrows
selfneedswhere Self: 'a. - Type-parameter GATs need
whereclauses for any bound the assigned type relies on.
Exercise
This trait fails to compile. Name the two problems and write the corrected trait. trait Source { type Out<'a>; fn get(&mut self) -> Self::Out; }
Show answer
First, Self::Out is used without its lifetime argument, so the compiler reports missing generics. Second, Out<'a> appears in a method that borrows self, so the declaration needs where Self: 'a. Corrected: trait Source { type Out<'a> where Self: 'a; fn get(&mut self) -> Self::Out<'_>; }. Using fn get<'a>(&'a mut self) -> Self::Out<'a> is equivalent.
Exercise
Implement Source from the previous exercise for struct Words { text: String }, so that get returns &str borrowed from text. What is the line that assigns Out?
Show answer
type Out<'a> = &'a str where Self: 'a;. The method body can be &self.text. The where clause follows the assigned type, and the lifetime 'a ties the returned &str to the borrow of self.