Document connection between Iterator::skip and Iterator::nth

From my forum question:

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 [… but] I cannot find a public API to create a Skip except by calling Iterator::skip.

Is this impossible?

It’s easy, according to @scottmcm: implement my own Iterator::nth method, and I will get a skip implementation for free.

In retrospect it makes sense, but it was not obvious to me at all just from reading the docs. It is not mentioned in the Implementing Iterators section of the API, or the docs for either method. And as the link in my post suggests, trying to work my way around the ownership of the APIs led me quite far afield.

Admittedly it’s not the most common case, but I think it would save others time if the standard library at least mentioned this somewhere.

EDIT: fixed forum link which changed its name when I marked it solved.

1 thought on “Document connection between Iterator::skip and Iterator::nth

  1. What about adding this line of text at the end of the “Implementing Iterator” section?

    Also note that Iterator provides a default implementation of methods such as nth and fold
    which call next internally. However, it is also possible to write a custom implementation of
    methods such as nth and fold if an iterator is able to compute them more efficiently without calling

    Feel free to adjust the text or make something up yourself 🙂 If you agree I will create a PR for this.

Comments are closed.