How to Use the Lending Iterator Pattern in Rust

Rust uses standard iterators returning references to borrow items safely without moving them.

Rust does not have a built-in 'Lending Iterator' pattern; instead, use the standard Iterator trait with references to borrow items without moving them. Implement the Iterator trait for your custom type and return &T (a reference) from the next method to allow borrowing elements from a collection.

struct MyIter<'a> {
    items: &'a [i32],
    index: usize,
}

impl<'a> Iterator for MyIter<'a> {
    type Item = &'a i32;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index >= self.items.len() {
            return None;
        }
        let item = &self.items[self.index];
        self.index += 1;
        Some(item)
    }
}

fn main() {
    let data = vec![1, 2, 3];
    let mut iter = MyIter { items: &data, index: 0 };
    while let Some(&val) = iter.next() {
        println!("{}", val);
    }
}