Implement DoubleEndedIterator Manually

Add next and next_back to a custom inclusive range so consumers can walk it forward with next or in reverse with rev, one step at a time.

RustCli Tooling

Code

rustsnippet
43 lines
// 自定义闭区间 [front, back] 的双向游标:分页工具常需要正反两个方向
#[derive(Clone, Copy)]
struct PageCursor {
    front: u16,
    back: u16,
}

impl Iterator for PageCursor {
    type Item = u16;

    fn next(&mut self) -> Option<u16> {
        if self.front > self.back {
            return None;
        }
        let page = self.front;
        self.front += 1;
        Some(page)
    }
}

impl DoubleEndedIterator for PageCursor {
    fn next_back(&mut self) -> Option<u16> {
        if self.front > self.back {
            return None;
        }
        let page = self.back;
        self.back -= 1;
        Some(page)
    }
}

fn main() {
    let cursor = PageCursor { front: 1, back: 4 };
    println!("forward: {:?}", cursor.clone().collect::<Vec<u16>>());
    println!("reverse: {:?}", cursor.rev().collect::<Vec<u16>>());

    // 两端交替消费:next 与 next_back 相向而行,在中点相遇
    let mut mixed = cursor;
    let first = mixed.next();
    let last = mixed.next_back();
    println!("alternating: {:?} .. {:?}", first, last);
    println!("rest: {:?}", mixed.collect::<Vec<u16>>());
}

Two methods, two directions

PageCursor { front, back } implements Iterator::next (yield self.front, then self.front += 1) and DoubleEndedIterator::next_back (yield self.back, then self.back -= 1), both stopping with None once front > back. The shared exit check means the two cursors walk toward each other and cannot pass — rev() works for free once next_back exists, because DoubleEndedIterator provides it in terms of next_back.

What the demo prints

forward: [1, 2, 3, 4]
reverse: [4, 3, 2, 1]
alternating: Some(1) .. Some(4)
rest: [2, 3]

forward collects a clone of the cursor; reverse is the same cursor through cursor.rev(). The alternating pair consumes one element from each end — mixed.next() takes 1, mixed.next_back() takes 4 — leaving front at 2 and back at 3, which is exactly the rest: line when the remainder is collected.

The line that walks backward

let page = self.back;
self.back -= 1;
Some(page)

next_back mirrors next step for step — same guard, opposite field — which is all the trait needs to treat the cursor as bidirectional.

Interactive Tools for This Topic

FAQ

What does Implement DoubleEndedIterator Manually print when run?
Execute the whole file; each printed line is prefixed with a label like `forward:`, `reverse:`, `alternating:`.