1

I'm trying to build an iterator over the rows of a table, and I'm using a lib that reads this. That lib had a proper iterator. I want to know how to chain these two iterators, 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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

@CyroAlves you can vote on answers to your own questions without needing rep. If you accept a helpful answer with the check button, you even earn a couple points. see the create a post privileges to know what you can do!
@JeremyMeadows I'm not sure? I think even on your posts you cannot upvote until 15 rep. But I long forgot that :)
if that's the case, they should change that page I linked to not suggest "As you see new answers to your question, vote up the helpful ones by clicking the upward pointing arrow to the left of the answer." I also forget though xD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.