rust / expert
Snippet
Generic Associated Types (GATs) for Iteration
Generic Associated Types allow associated types to carry a lifetime or type parameter. This is essential for 'Lending Iterators', where the item yielded by the iterator borrows from the iterator itself, a pattern that standard Iterators cannot express efficiently.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
trait LendingIterator {type Item<'a> where Self: 'a;fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;}struct MyStream(Vec<u32>);impl LendingIterator for MyStream {type Item<'a> = &'a u32;fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {self.0.get(0) // Simplified logic}}
Breakdown
1
type Item<'a> where Self: 'a;
Defines an associated type that is generic over a lifetime 'a, bound by the caller.
2
fn next<'a>(&'a mut self)
The method signature ties the lifetime of the returned Item to the borrow of the iterator.