Rust Windows & Chunks
windows and chunks are two slice methods for viewing groups. windows views overlapping groups of neighbours.
windows slides one step at a time
Each group holds n neighbours, and the next group starts one step later — so the groups overlap:
let nums = [1, 2, 3, 4];
for w in nums.windows(2) {
println!("{w:?}");
}The gap between neighbours
windows is the tool for questions about neighbours. pair[0] and pair[1] read the two members of a group:
let readings = [10, 14, 13];
for pair in readings.windows(2) {
println!("gap = {}", pair[1] - pair[0]);
}chunks cuts without overlapping
chunks gives piles of n that never overlap. The last pile may be smaller than the rest:
let jobs = [1, 2, 3, 4, 5];
for pile in jobs.chunks(2) {
println!("{pile:?}");
}chunks_exact leaves the leftover over
Use chunks_exact when a short last pile should not be served as a pile. The leftover is still there afterwards, as the remainder:
let data = [1, 2, 3, 4, 5];
let mut it = data.chunks_exact(2);
for pile in &mut it {
println!("{pile:?}");
}
println!("leftover = {:?}", it.remainder());Example
fn main() {
let stops: [(f64, f64); 3] = [(0.0, 0.0), (3.0, 4.0), (3.0, 10.0)];
let total: f64 = stops.windows(2).map(|pair| {
let (x1, y1) = pair[0];
let (x2, y2) = pair[1];
((x2 - x1).powi(2) + (y2 - y1).powi(2)).sqrt()
}).sum();
println!("route length = {}", total);
let jobs: Vec<i32> = (1..=7).collect();
for batch in jobs.chunks(3) {
println!("batch = {:?}", batch);
}
}Key points
- Both are methods on slices.
- Call them on an array.
- Call them on a Vec, which borrows as a slice.
- Or call them on any &[T]
In this example, stops holds three points on a map. windows(2) hands over each neighbouring pair: first (0, 0) with (3, 4), then (3, 4) with (3, 10). The map step works out the length of each leg with Pythagoras. The first leg is 5 and the second is 6. sum() adds them to 11. Below, chunks(3) cuts seven jobs into piles of three. The piles print as [1, 2, 3] and [4, 5, 6]. The last pile holds the single leftover job, [7].
Note
windows and chunks copy nothing.
Each group is a view into the same data.
So both are cheap enough to use inside any pipeline.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does [10, 20, 30].windows(2) produce?