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?
You can achieve a similar solution as Lukas Kalbertodt's itertools example using only the standard library:
Result:
If you don't actually need the
Vec
of each chunk, you can omit thecollect
call and operate directly on the iterator created byby_ref
.See also:
There is no such helper method on the
Iterator
trait directly. However, there are two main ways to do it:Use the
[T]::chunks()
method (which can be called on aVec<T>
directly). However, it has a minor difference: it won't produceNone
, but the last iteration yields a smaller slice.Example:
Result:
Use the
Itertools::chunks()
method from the crateitertools
. This crate extends theIterator
trait from the standard library so thischunks()
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 containingNone
s.Example:
Result: