Reputation: 222
I would like to have something like:
fn drain_in_chunks<T>(mut v: Vec<T> {
for chunk in v.drain.chunks(2){
do_something(chunk)}
}
where I remove chunks of size two from v
in each iteration. Why I want to do this is, because I want to move the chunks into a function. However, I can't move elements from a vector without removing them.
I could do this, but it feels to verbose.
for (i, chunk) in v.chunks(2).enumerate().zip(0..) {
v.drain(i*2..(i+1)*2);
do_something(chunk)
}
Any more elegant solutions?
Upvotes: 1
Views: 309
Reputation: 70950
You can use itertools
's tuples()
:
use itertools::Itertools;
fn drain_in_chunks<T>(mut v: Vec<T>) {
for (a, b) in v.drain(..).tuples() {
do_something([a, b]);
}
}
Upvotes: 1