[Solved] Custom impl for Iterator::skip

Consider an iterator that does two things:

  1. Read data from a data source.
  2. Perform a complex calculation on the data read.

This means that next is computationally expensive, but skip could be cheap if implemented by hand. It could just do step 1 and throw the data away without doing step 2.

I have tried various ways to do this, such as:

impl Iterator for T {
    fn skip(mut self, n: usize) -> Skip<Self> {
        for _ in 0..n {
            self.read_next(); // internal function to just read
        std::iter::Iterator::skip(self, 0)

But warnings indicate it is not doing what I hoped. In fact, research has convinced me there is no syntax in Rust for this at all.

On the other hand, I cannot take the advice in the link, because I cannot find a public API to create a Skip<T> except by calling Iterator::skip.

Is this impossible?

skip uses nth, so just override nth for your iterator.

Thanks, that's exactly what I was looking for!

It would be nice to document that connection somewhere. I didn't see it mentioned in Iterator::skip; Iterator::nth doesn't mention you get a better skip implementation; and the Implementing Iterators section didn't mention this at all.

I will open a Rust Issue for that, though. I consider this solved.

Issue opened.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.