How to skip forward in iterator without moving it?

I am looping over an iterator and inside the loop I would occasionally like to skip forward a a few steps. But something like skip() won't work since it apparently takes ownership of the iterator. Is there some easy way of skipping forward a bunch of steps in the iteration without having to call next() lots of times in a row?

Code would be something like:

let mut buffer: Vec<u8> = // Some data
let mut buff_iter = buffer.into_iter();
while let Some(x) = {
  // Do lost of stuff

  // If some condition is true

Use nth.


I'd just like to add to @stebalien's answer, you should substract one from the number of items to skip to use nth, i.e. iter.nth(0) to skip one item, iter.nth(1) to skip two etc. Just to avoid a catch here.

1 Like

Itertools::dropping is what you want.

It works similarly to .skip(n) except it is eager and preserves the iterator type.

Thank you. Lots of working suggestions.

@DanielKeep Is there any specific reason you suggested dropping instead of dropn from itertools?

Because I don't have every method in every library memorised and I found dropping first.