Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I continue using an iterator after calling take? [duplicate]

Tags:

iterator

rust

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?

like image 908
Timmmm Avatar asked Feb 10 '26 19:02

Timmmm


1 Answers

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.
}
like image 51
Timmmm Avatar answered Feb 13 '26 08:02

Timmmm