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.
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
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.
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
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
nand sizek,windows(k)yieldsn - k + 1items (or 0),chunks(k)yieldsceil(n / k),chunks_exact(k)yieldsn / k. chunkskeeps a shorter last piece;chunks_exactskips it and gives it viaremainder(), which suits fixed-size records and SIMD-style loops.splitremoves the separators, and yields empty slices for adjacent or leading/trailing separators (see the0, 0in the example).split_inclusivekeeps the separator at the end of each piece.- Mutable chunks are disjoint, so
chunks_mutis the safe way to hand different parts of a slice to different threads or loop passes. There is nowindows_mut, because overlapping mutable views would alias. chunk_bystabilized in Rust 1.77. It replaces the older "group consecutive equal items" loops.- Fixed-size pieces:
chunks_exactgives them as slices;as_chunks::<N>()(Rust 1.88 and later) gives them as&[T; N]arrays. - Strings:
windowsworks on&[u8]and&[char]only;strhas nowindows. Collect chars into aVec<char>first, or usechar_indicesand slicing. - Do not mutate the vector while iterating these views; they borrow it.