I have let my_vec = (0..25).collect::<Vec<_>>()
and I would like to split my_vec
into iterators of groups of 10:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
[20, 21, 22, 23, 24, None, None, None, None, None];
Is it possible to do that with iterators in Rust?
There is no such helper method on the Iterator
trait directly. However, there are two main ways to do it:
[T]::chunks()
method (which can be called on a Vec<T>
directly). However, it has a minor difference: it won't produce None
, but the last iteration yields a smaller slice. For always-exact slices that omit the final chunk if it's incomplete, see the [T]::chunks_exact()
method. let my_vec = (0..25).collect::<Vec<_>>();
for chunk in my_vec.chunks(10) {
println!("{:02?}", chunk);
}
Result:
```none
[00, 01, 02, 03, 04, 05, 06, 07, 08, 09]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
```
Itertools::chunks()
method from the crate itertools
. This crate extends the Iterator
trait from the standard library so this chunks()
method works with all iterators! Note that the usage is slightly more complicated in order to be that general. This has the same behavior as the method described above: in the last iteration, the chunk will be smaller instead of containing None
s. extern crate itertools;
use itertools::Itertools;
for chunk in &(0..25).chunks(10) {
println!("{:02?}", chunk.collect::<Vec<_>>());
}
Result:
```none
[00, 01, 02, 03, 04, 05, 06, 07, 08, 09]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[20, 21, 22, 23, 24]
```