skip to content

In Rust, why can't an `Iterator` yield overlapping `&mut` windows into its own buffer, and how does a generic associated type `type Item<'a>` fix it?

level: seniorimportance: nice to knowfreq 25%

answer

  1. Item cannot see next's borrow
  2. items may all be alive at once
  3. lifetime parameter on the associated type
  4. where Self: 'a is required
  5. no for loop, no dyn

basics

~20 s

Iterator's Item is fixed per impl and cannot name the lifetime of next's &mut self borrow, so items may outlive the call and overlapping &mut windows would alias. A generic associated type ties each item to that borrow.

solid answer

~50 s

`Iterator::next(&mut self) -> Option<Self::Item>` returns an `Item` that is unrelated to the borrow of the iterator, so a caller may keep every item at once, for example by `collect()`. Overlapping `&mut [T]` windows would then alias, and an impl with `type Item = &'s mut [T]` that returns a window from `next` is rejected with `lifetime may not live long enough`; std's own docs say there is no `windows_mut` because `Iterator` cannot represent the lifetimes. A **generic associated type** (stable since Rust 1.65) gives the associated type its own parameter: `type Item<'a> where Self: 'a;` with `fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>`. Each item now borrows the iterator, so the caller must release it before calling `next` again (keeping two is E0499). The `where Self: 'a` clause is required. The price: such a trait is not std's `Iterator`, so `for` loops and adapters do not apply, and a GAT makes the trait not dyn compatible.

code

rust · 32 lines
rust
trait LendingIterator {
    type Item<'a>
    where
        Self: 'a;
    fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}

// Overlapping mutable windows: each one borrows the iterator itself.
struct WindowsMut<'s, T> {
    data: &'s mut [T],
    size: usize,
    pos: usize,
}

impl<'s, T> LendingIterator for WindowsMut<'s, T> {
    type Item<'a> = &'a mut [T] where Self: 'a;

    fn next<'a>(&'a mut self) -> Option<&'a mut [T]> {
        let w = self.data.get_mut(self.pos..self.pos + self.size)?;
        self.pos += 1;
        Some(w)
    }
}

fn main() {
    let mut buf = [1, 2, 3, 4];
    let mut it = WindowsMut { data: &mut buf, size: 2, pos: 0 };
    while let Some(w) = it.next() {
        w[1] += w[0]; // each window may be mutated, then released
    }
    println!("{buf:?}"); // prefix sums: [1, 3, 6, 10]
}

go deeper

for a junior

Recall that std offers windows but no windows_mut, and that Iterator's items are allowed to outlive the next call that produced them.

for a middle

Explain why Item cannot name the &mut self borrow, and why that makes overlapping mutable windows unsound under the plain Iterator trait.

for a senior

Write the GAT trait with its required where Self: 'a, read E0499 as the guarantee working, and state the costs: no for loops, no adapters, no dyn.

for a principal

Weigh a lending interface against plain Iterator for a shared API: it rules out collect and std adapters for every caller, so reserve it for cases where items must borrow the iterator.

## Why plain `Iterator` cannot lend The standard `Iterator` trait has one associated type and one required method: ```rust pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } ``` `Item` is fixed **once per impl**. It may contain a lifetime, but only one the impl already has in scope, such as the `'s` in `WindowsMut<'s, T>`, or `'static`. It cannot mention the lifetime of the `&mut self` borrow in a particular call to `next`, because that lifetime is different on every call and the associated type has no parameter to receive it. The consequence is a promise to callers: **items do not borrow the iterator**. A caller may call `next` repeatedly and keep every result alive at the same time, which is exactly what `collect()` does. For shared views that is harmless; `slice.windows(2)` yields overlapping `&[T]` windows, and shared references may overlap. For `&mut [T]` it would be unsound, because two live overlapping `&mut` windows would alias the same elements. rustc enforces this. Writing `type Item = &'s mut [T];` and returning `self.data.get_mut(...)` from `next` fails with `lifetime may not live long enough`: the method was supposed to return data with lifetime `'s`, but it can only hand out data borrowed for the shorter `&mut self` lifetime. The standard library documents the same limit on `slice::windows`: because the `Iterator` trait cannot represent the required lifetimes, there is no `windows_mut`, though a lending-iterator analog is possible. ## What a generic associated type adds A **generic associated type (GAT)**, stabilised in Rust 1.65, is an associated type with its own generic parameters (lifetimes, types or consts). The Reference's term is exactly that: associated types that include generic parameters and where clauses. A lending iterator uses a lifetime parameter: ```rust trait LendingIterator { type Item<'a> where Self: 'a; fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>; } ``` Now each call's borrow `'a` flows into the item type. The impl for overlapping windows writes `type Item<'a> = &'a mut [T] where Self: 'a;` and returns `self.data.get_mut(self.pos..self.pos + self.size)` from `next`, which compiles because the window is borrowed for `'a`, not for `'s`. What changes for the caller: - **One item at a time.** The returned item keeps the iterator mutably borrowed. Keeping the result of one `next` while calling `next` again is **E0499**; for an iterator bound to `it`, rustc prints `cannot borrow it as mutable more than once at a time`. - **Loop with `while let`.** `while let Some(w) = it.next() { ... }` works, because each `w` ends before the next call. ## The required `where Self: 'a` Leaving out the where clause is rejected: rustc reports `missing required bound on Item` and suggests `where Self: 'a`, noting that the bound is currently required to ensure impls have maximum flexibility. The Reference explains the rule: because `next` takes `&'a mut self`, the compiler can prove `Self: 'a` inside `next`, and any bound provable on a function where the GAT appears must also be written on the GAT itself. The rule may be loosened in future releases, but on Rust 1.99 it is enforced. ## What you give up | Capability | `Iterator` | GAT-based lending trait | |---|---|---| | `for` loops | yes, through `IntoIterator` | no: `for x in lender` is E0277, not an iterator | | std adapters (`map`, `filter`, `collect`) | yes | no, unless you write them | | keeping several items alive | yes | no, by design | | use as `dyn Trait` | yes, with `Item` specified | no: E0038, the trait contains a generic associated type | | in the standard library | yes | no such trait in std | Two further points interviewers probe: 1. **Bounds get heavier.** Requiring every item to be `Debug` means quantifying over the lifetime, for example `where for<'a> I::Item<'a>: Debug`, which is heavier to write and to read than the plain `I::Item: Debug` an ordinary iterator needs. 2. **GATs are broader than lending.** The same feature lets a trait describe a family of types, such as `type Pointer<T>` for a trait abstracting over `Rc` and `Arc`; lending iterators are simply the motivating example. ## When to reach for it - The item must borrow mutable state from the iterator itself (overlapping mutable windows, a reused line buffer, a database cursor that overwrites one row). - Collecting or keeping items is not needed. - Callers accept `while let` instead of `for` and losing the adapter ecosystem. If items can own their data or share it immutably, the plain `Iterator` remains the better interface.

  • What happens in Rust if a lending-iterator caller keeps the result of one `next` call and calls `next` again?
    rustc rejects it with E0499 (for an iterator bound to `it`: `cannot borrow it as mutable more than once at a time`), because each item is typed `Self::Item<'a>` and keeps the `&'a mut self` borrow alive. That rejection is the guarantee: no two items from the iterator can coexist, so overlapping `&mut` windows never alias.
  • Why can't a GAT-based lending iterator be used as `dyn LendingIterator` in Rust?
    The Reference's dyn-compatibility rules forbid associated types with generics, so even `dyn for<'a> LendingIterator<Item<'a> = &'a u8>` fails with E0038, noting that the trait contains generic associated type `Item`. Callers needing dynamic dispatch must use generics instead, or a separate dyn-compatible trait.

  • Generic associated types still require a nightly compiler.
  • A lending iterator works in a for loop like any Iterator.
  • The where Self: 'a clause on the GAT is optional decoration.
  • Declaring type Item = &'s mut [T] with the struct's lifetime fixes mutable windows.
  • A lending iterator lets you keep items from two successive next calls.

Assumes Rust 1.99; generic associated types are stable since Rust 1.65, and the required where Self: 'a clause is still enforced on 1.99.