Sub topic 11
Why GATs need where Self: 'a
This chapter explains the where Self: 'a clause that nearly every generic associated type (GAT) with a lifetime parameter carries. It assumes you can read the lending iterator from the previous chapter: a trait with type Item<'a> and a next method that takes &'a mut self. It also assumes you know what T: 'a means (the type T contains no references that end before 'a).
The error you hit first
Write a lending iterator the obvious way and leave the clause out:
trait LendingIterator {
type Item<'a>;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}The compiler rejects the declaration. The message, abridged, reads:
error: missing required bound on `Item`
|
| type Item<'a>;
| ^^^^^^^^^^^^^- help: add the required where clause: `where Self: 'a`
|
= note: this bound is currently required to ensure that impls have maximum flexibilityThe fix is to put the clause on the declaration:
type Item<'a> where Self: 'a;The rest of the chapter explains what the clause means, why the compiler insists on it, and what it costs.
What the clause says
Self: 'a means that the implementing type outlives the lifetime 'a. Every reference stored inside Self stays valid for at least 'a.
On a GAT, the clause restricts when the projection <Self as LendingIterator>::Item<'a> may be named. Callers can only write Item<'a> for lifetimes 'a that Self outlives. In exchange, an implementor may assume Self: 'a when it defines Item<'a>.
That assumption matters because lending items usually borrow from the implementor. Take type Item<'a> = &'a mut [T] inside impl<'t, T> LendingIterator for WindowsMut<'t, T>. The type &'a mut [T] is only well-formed if [T]: 'a, which means T: 'a. The impl cannot prove that from nothing, because 'a is a fresh lifetime parameter that could be arbitrarily long. The clause supplies the missing fact. From WindowsMut<'t, T>: 'a the compiler derives T: 'a, and the item type is valid.
Why the compiler cannot infer it
Ordinary function signatures get this fact for free. If a function takes &'a mut Self, the compiler assumes Self: 'a. These are called implied bounds, and they exist because a reference &'a T can only be created when T: 'a. That is why next<'a>(&'a mut self) is fine inside the trait.
An associated type declaration has no such argument. In type Item<'a>; the lifetime 'a appears from nowhere, with no reference tying it to Self. Without a stated relationship, the trait would promise that Item<'a> exists for every 'a, including lifetimes longer than Self lives. An implementation like &'a mut [T] could then hand out a reference to data that is already gone.
The clause closes that gap in the trait itself. It is a design decision with two sides.
- The implementor side. The impl may assume
Self: 'a, so&'a mut [T]and&'a strborrowed fromselfare allowed. - The user side. Anyone who names
L::Item<'a>must showL: 'a.
The note in the error message says the bound is required for "maximum flexibility of impls". The compiler is conservative: it requires the clause whenever a method of the trait uses the GAT with a lifetime tied to Self through the signature. Otherwise a later change, such as adding such a method, could break every implementor. Requiring the clause up front keeps trait definitions stable.
A complete example
The program below defines the trait with the clause, implements it for a mutable windowing type, and stores an item inside a struct. The struct is where the caller-side obligation becomes visible.
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
struct WindowsMut<'t, T> {
slice: &'t mut [T],
start: usize,
size: usize,
}
impl<'t, T> LendingIterator for WindowsMut<'t, T> {
type Item<'a> = &'a mut [T] where Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
let end = self.start + self.size;
if end > self.slice.len() {
return None;
}
let window = &mut self.slice[self.start..end];
self.start += 1;
Some(window)
}
}
struct Holder<'a, L: LendingIterator + 'a> {
current: Option<L::Item<'a>>,
}
fn count_all<L: LendingIterator>(iter: &mut L) -> usize {
let mut n = 0;
while iter.next().is_some() {
n += 1;
}
n
}
fn main() {
let mut data = [1, 2, 3];
let mut windows = WindowsMut { slice: &mut data, start: 0, size: 2 };
let holder = Holder::<WindowsMut<i32>> { current: windows.next() };
println!("{:?}", holder.current);
let mut other = [4, 5, 6, 7];
let mut more = WindowsMut { slice: &mut other, start: 0, size: 2 };
println!("{}", count_all(&mut more));
}The program prints Some([1, 2]) and then 3.
Two details are worth studying.
count_allnever mentionsL: 'a. The calliter.next()takes&mut Lfor some anonymous lifetime, and the implied boundL: 'acomes with it.HolderneedsL: 'awritten out. A struct definition gets no implied bounds from field types that go through a projection. Without+ 'a, the compiler reports that the parameter typeLmay not live long enough, which is the user-side obligation from the previous section.
Writing the clause in the impl
The impl must restate where Self: 'a when its item type needs the fact. For &'a mut [T] it does. If the item type does not depend on it, for example type Item<'a> = &'a str for a struct that owns a String, the type is well-formed anyway. Repeating the clause there is still harmless, and it keeps impls uniform.
The impl may not add clauses that the trait lacks. A clause such as where T: 'static on the impl's Item<'a> would be stricter than the trait's promise. The compiler rejects it, because callers who know only the trait could not satisfy it.
Costs and sharp edges
The clause creates a known limitation. Suppose you want to say "every item of this iterator implements Debug". The natural bound is higher-ranked:
where for<'a> L::Item<'a>: DebugThis asks the compiler to prove the bound for all 'a, including 'a = 'static. Because naming L::Item<'static> requires L: 'static, the bound can end up forcing L: 'static. A lending iterator over a local slice then stops working with that function. The Rust team documented this in the stabilization report for GATs in Rust 1.65, and it is the main reason some GAT-heavy code needs a different shape. The usual workarounds are to bound the concrete item type directly, for example with for<'a> LendingIterator<Item<'a> = &'a mut [i32]>, or to accept a 'static requirement where it is harmless. Check the current compiler behaviour for your exact bound, since these corners have been improving.
A second consequence concerns trait objects. A GAT with a where clause generally makes the trait not dyn compatible, so dyn LendingIterator is not available. That limitation is covered in the next chapter.
The table summarizes where the obligation lands.
| Place | Who needs `Self: 'a` | How it is satisfied |
|---|---|---|
| Trait declaration | Written by the trait author | `type Item<'a> where Self: 'a;` |
| `impl` of the GAT | Assumed by the implementor | Restate `where Self: 'a` on the item |
| Function with `&'a mut L` | Needed by the caller side | Implied by the reference type |
| Struct or alias naming `L::Item<'a>` | Needed by the user | Write `L: 'a` explicitly |
| `for<'a>` bound on the item | Needed for all `'a` | Often forces `L: 'static` |
Exercise
A colleague deletes where Self: 'a from the trait declaration of a lending iterator and the compiler reports "missing required bound on Item". They say "the trait methods already take &'a mut self, so this must be redundant". What is wrong with that reasoning?
Show answer
The implied bound Self: 'a comes from the reference type in the method signature, and it holds only inside that method. The associated type declaration type Item<'a>; has no such argument, so 'a is unconstrained there. Without the clause, the trait would promise Item<'a> for lifetimes longer than Self lives, and implementors that borrow from self could not prove their item type is well-formed. The compiler requires the clause on the declaration so that implementors may assume it and users must prove it.
Exercise
In the example program, remove + 'a from struct Holder<'a, L: LendingIterator + 'a>. Which error do you expect, and why does count_all need no equivalent annotation?
Show answer
You expect an error saying the parameter type L may not live long enough, because naming L::Item<'a> requires L: 'a and a struct definition gets no implied bounds. count_all calls iter.next() through &mut L, and a reference to L carries the implied bound that L outlives the borrow, so the clause is satisfied automatically.