4

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
  • 326,504
  • 69
  • 892
  • 1,159
Timmmm
  • 78,116
  • 55
  • 321
  • 425

1 Answers1

5

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
  • 326,504
  • 69
  • 892
  • 1,159
Timmmm
  • 78,116
  • 55
  • 321
  • 425