Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Collections

Rust slice windows, chunks and split

Reference for Rust slice windows, chunks, chunks_exact, rchunks, split, chunk_by: sizes, remainders, panics and examples.

These slice methods return iterators over sub-slices, so you can process data in groups without copying. windows(n) yields every run of n consecutive elements, overlapping. chunks(n) splits the slice into non-overlapping pieces of up to n elements. split(pred) cuts the slice at every element matching a predicate, and chunk_by groups neighbors that satisfy a relation.

Every item is a borrowed &[T] (or &mut [T] for the _mut variants), so nothing is allocated except the iterator itself.

Rust
let v = [1, 2, 3, 4, 5];
let sums: Vec<i32> = v.windows(2).map(|w| w[0] + w[1]).collect();
// [3, 5, 7, 9]

Try it

Rust windows and chunks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust split and chunk_by

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl<T> [T] {
    pub fn windows(&self, size: usize) -> Windows<'_, T>;
    pub fn chunks(&self, chunk_size: usize) -> Chunks<'_, T>;
    pub fn chunks_exact(&self, chunk_size: usize) -> ChunksExact<'_, T>;
    pub fn rchunks(&self, chunk_size: usize) -> RChunks<'_, T>;
    pub fn chunks_mut(&mut self, chunk_size: usize) -> ChunksMut<'_, T>;
    pub fn split<F: FnMut(&T) -> bool>(&self, pred: F) -> Split<'_, T, F>;
    pub fn chunk_by<F: FnMut(&T, &T) -> bool>(&self, pred: F) -> ChunkBy<'_, T, F>;
}
Name Description
size, chunk_size Group length. Must not be zero.
pred For split, returns true for a separator element. For chunk_by, returns true while two neighbors belong to the same group.

Returns: an iterator of sub-slices. windows and chunks also implement DoubleEndedIterator and ExactSizeIterator.

Panics: windows, chunks, chunks_exact and rchunks panic when the size is 0. If a window is larger than the slice, windows yields nothing.

Usage notes

  • Counts: for length n and size k, windows(k) yields n - k + 1 items (or 0), chunks(k) yields ceil(n / k), chunks_exact(k) yields n / k.
  • chunks keeps a shorter last piece; chunks_exact skips it and gives it via remainder(), which suits fixed-size records and SIMD-style loops.
  • split removes the separators, and yields empty slices for adjacent or leading/trailing separators (see the 0, 0 in the example). split_inclusive keeps the separator at the end of each piece.
  • Mutable chunks are disjoint, so chunks_mut is the safe way to hand different parts of a slice to different threads or loop passes. There is no windows_mut, because overlapping mutable views would alias.
  • chunk_by stabilized in Rust 1.77. It replaces the older "group consecutive equal items" loops.
  • Fixed-size pieces: chunks_exact gives them as slices; as_chunks::<N>() (Rust 1.88 and later) gives them as &[T; N] arrays.
  • Strings: windows works on &[u8] and &[char] only; str has no windows. Collect chars into a Vec<char> first, or use char_indices and slicing.
  • Do not mutate the vector while iterating these views; they borrow it.