Custom Iterator Borrows A Slice

Implement Iterator with a lifetime parameter so a hand-written iterator lends &a T items while the underlying slice keeps its owner.

RustData Integrity

Code

rustsnippet
29 lines
struct SliceIter<'a, T> {
    items: &'a [T],
    cursor: usize,
}

impl<'a, T> Iterator for SliceIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.items.get(self.cursor);
        if item.is_some() {
            self.cursor += 1;
        }
        item
    }
}

fn main() {
    let lines = vec![String::from("build"), String::from("sign"), String::from("upload")];

    // 迭代器只借用 slice:遍历期间 lines 的所有权仍在当前作用域
    let mut rows = SliceIter { items: &lines, cursor: 0 };
    while let Some(row) = rows.next() {
        println!("row: {row}");
    }

    // 借用结束原集合完好:没有被 move,也没有被消费
    println!("total: {}", lines.len());
}

How execution unfolds

Everything effective happens in the functions next and main — everything else is wiring.

The file repeats itself only inside while let Some(row) = rows.next().

Caveats

  • Ready as-is on a bare install of the language.

Putting it to use

Signature: fn next(&mut self) -> Option<Self::Item>

The run prints row:, total: — each prefix names the step that produced it.

Execute the file and main walks through next, in that order.

Core lines

while let Some(row) = rows.next() {
    println!("row: {row}");
}
fn next(&mut self) -> Option<Self::Item> {
    let item = self.items.get(self.cursor);
    if item.is_some() {
        self.cursor += 1;
    }
    item
}

Interactive Tools for This Topic

FAQ

What does Custom Iterator Borrows A Slice print when run?
The script runs standalone; its 2 labeled outputs include `row:`, `total:`.