There is a method already existing for slices:
pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>
Returns an iterator over chunk_size
elements of the slice at a time, starting at the beginning of the slice.
The chunks are slices and do not overlap. If chunk_size
does not divide the length of the slice, then the last chunk will not have length chunk_size
.
There is also chunks_mut
for mutability as well as chunks_exact
and chunks_exact_mut
if the last chunk has to respect the size n
, along with the unsafe as_chunks_unchecked
in case we assume there is no remainder, see below example:
fn main() {
let v: [u8; 5] = *b"lorem";
let n = 2;
let chunks = v.chunks(n);
let chunks_list: Vec<&[u8]> = chunks.collect();
println!("{:?}", chunks_list);
}
Using a slice instead of vectors has some benefits, notably avoiding the overhead of copying.