11

I want to collect a few items from an iterator, then iterate through the rest, something like this:

let iterator = text.split_whitespace();
let first_ten_words = iterator.take(10).collect();

for word in iterator {
    // This should iterate over the remaining words.
}

This doesn't work because take() consumes the iterator.

Obviously I can use split_whitespace() twice and skip(10) but I assume that will do the splitting of the first 10 words twice, and therefore be inefficient.

Is there a better way to do it?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Timmmm
  • 88,195
  • 71
  • 364
  • 509

1 Answers1

12

You can use .by_ref() like this:

let iterator = text.split_whitespace();
let first_ten_words = iterator.by_ref().take(10).collect();

for word in iterator {
    // This should iterate over the remaining words.
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Timmmm
  • 88,195
  • 71
  • 364
  • 509