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?
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With