Cyro Alves
Cyro Alves

Reputation: 15

Iterator inside iterator

I'm trying to build an iterator over the rows of a table and i'm using a lib that read this. That lib had a proper iterator. I want to know how to chain these two iterator, i mean, when i call next on my iterator the next of the lib calls too.

impl Iterator for MyStruct {
  type Item = item;

  fn next(&mut self) -> Option<Self::Item> {
    records().next()
  }
}

I did that, but this calls only the first next every time, i want all the rows of the lib iterator

Upvotes: 0

Views: 164

Answers (1)

Finomnis
Finomnis

Reputation: 22396

By calling records() inside of the next() function, you are creating a new iterator every time, so you start from the beginning at every next() call.

You need to store the records iterator in the struct and then re-use it instead of re-creating it every time. That way it keeps its state between calls.

Look at this example:

fn records() -> impl Iterator<Item = i32> {
    (1..5).into_iter()
}

struct MyStruct {
    records_iter: Box<dyn Iterator<Item = i32>>,
}

impl MyStruct {
    fn new() -> Self {
        Self {
            records_iter: Box::new(records()),
        }
    }
}

impl Iterator for MyStruct {
    type Item = i32;

    fn next(&mut self) -> Option<Self::Item> {
        self.records_iter.next()
    }
}

fn main() {
    let my_obj = MyStruct::new();

    for element in my_obj {
        println!("{}", element);
    }
}
1
2
3
4

Upvotes: 1

Related Questions