rust / expert
Snippet
Designing Lending Iterators Using Generic Associated Types
Standard Rust iterators yield items with lifetimes independent of the iterator itself. Lending Iterators (or streaming iterators) leverage Generic Associated Types (GATs) to tie the lifetime of the yielded item directly to the lifetime of the iterator's mutable borrow in `next`, enabling zero-copy windows over internal data buffers.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
pub trait LendingIterator {type Item<'a> where Self: 'a;fn next(&mut self) -> Option<Self::Item<'_>>;}pub struct SlidingWindow<'a, T> {slice: &'a [T],index: usize,width: usize,}impl<'a, T> LendingIterator for SlidingWindow<'a, T> {type Item<'b> = &'b [T] where Self: 'b;fn next(&mut self) -> Option<Self::Item<'_>> {if self.index + self.width <= self.slice.len() {let window = &self.slice[self.index..self.index + self.width];self.index += 1;Some(window)} else {None}}}
Breakdown
1
type Item<'a> where Self: 'a;
Declares a generic associated type that accepts a lifetime parameter, enabling the returned item to borrow from the iterator.
2
fn next(&mut self) -> Option<Self::Item<'_>>;
Ties the lifetime of the returned item directly to the lifetime of the mutable borrow of self.