How to iterate custom range

#1

As title said, I want to iterate the custom range of structure As bellow:

#[derive(PartialOrd)]
#[derive(PartialEq)]
pub struct Point {
        x: i32,
        y: i32,
}
struct Iter<T> {
        pointer: T,
        end: T,
}

impl Iterator for Iter<Point> {
        type Item = Point;
        fn next(&mut self) -> Option<Self::Item> {
                self.pointer.x += 1;
                self.pointer.y += 1;
                let p = Point {
                        x: self.pointer.x,
                        y: self.pointer.y,
                };
                if p > self.end {
                        None
                } else {
                        Some(p)
                }
        }
}

/*
impl ops::Range<Point> {
        fn iter(&self) -> Iter<Point>;
}
*/

I want to transfer Range<Point> to Iter<Pointer>, but can’t implement new method to Range out of the scope of itself.
The final usage I want is: Point(x:0, y:0)..Point(x:100, y:100).iter().map(...)

#2

To have range implement iterator, you need to implement Step for Point, as shown in this example. Please note that this is actually unstable and therefore requires nightly.

1 Like
#3

Thanks very much.It works well.:+1: