Rust

windows / chunks — Sliding & Fixed

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`windows(n)` yields every overlapping sub-slice of length n; `chunks(n)` yields non-overlapping chunks. Both work on slices for free, no extra crates.
Rust
Raw
fn main() {
    let v = vec![1, 2, 3, 4, 5, 6, 7];

    // windows(3) — overlapping
    for w in v.windows(3) {
        println!("window: {w:?}");
    }
    // [1, 2, 3]
    // [2, 3, 4]
    // [3, 4, 5] ...

    // chunks(3) — disjoint
    for c in v.chunks(3) {
        println!("chunk:  {c:?}");
    }
    // [1, 2, 3]
    // [4, 5, 6]
    // [7]

    // Moving average via windows
    let readings = vec![10.0, 12.0, 11.0, 15.0, 14.0, 18.0];
    let avgs: Vec<f64> = readings.windows(3)
        .map(|w| w.iter().sum::<f64>() / 3.0)
        .collect();
    println!("3-pt avg: {:?}", avgs);                // [11.0, 12.67, 13.33, 15.67]
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.