slice::chunks¶
Level: reference · for working programmers
One line: Non-overlapping groups of n elements, the last one possibly shorter.
Stable since 1.0.0. Its const form is still unstable.
Seven elements in chunks of three: [1, 2, 3], [4, 5, 6], [7]. The last chunk holds whatever is left, so a loop over chunks(n) must not assume chunk.len() == n — that is the off-by-one this corner of std is known for, and windows, which never yields a short one, is the other half of the confusion.
When a short tail would be wrong, chunks_exact ↗ yields only full chunks and hands the leftover back through remainder(). chunks_mut ↗ yields &mut [T].
The everyday job is rows out of a flat buffer: a grid stored as one Vec with width columns is grid.chunks(width). Grids and nested Vecs builds on that.
chunks(0) panics — chunk size must be non-zero.
Example¶
slice_chunks.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let v = [1, 2, 3, 4, 5, 6, 7];
for c in v.chunks(3) {
print!("{c:?} ");
}
println!();
println!("{} chunks; the last has {} element(s)",
v.chunks(3).len(), v.chunks(3).last().unwrap().len());
// chunks_exact drops the short tail and hands it back separately.
let mut exact = v.chunks_exact(3);
let full: Vec<_> = exact.by_ref().collect();
println!("{full:?} remainder {:?}", exact.remainder());
// Rows out of a flat grid: two columns.
let grid = [1, 2, 3, 4, 5, 6];
for row in grid.chunks(2) {
println!("{row:?}");
}
// The panic is caught here so the program can report it and go on.
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
let r = std::panic::catch_unwind(|| v.chunks(0).count());
std::panic::set_hook(hook);
println!("chunks(0) panicked: {}", r.is_err());
}
Verified output of slice_chunks.rs — regenerated by tools/run_examples.py, never hand-typed.
[1, 2, 3] [4, 5, 6] [7]
3 chunks; the last has 1 element(s)
[[1, 2, 3], [4, 5, 6]] remainder [7]
[1, 2]
[3, 4]
[5, 6]
chunks(0) panicked: true
See also¶
slice::windows— overlapping, and never shortslice::iter— one at a timeslice::get— one range, by hand