Skip to content

slice::windows

slice methods · Collections

Level: reference · for working programmers

One line: Every overlapping run of n consecutive elements — all of them full length.

pub fn windows(&self, size: usize) -> Windows<'_, T>

Stable since 1.0.0. Its const form is still unstable.

Four elements, windows of two: [1, 2], [2, 3], [3, 4]len - n + 1 windows, each exactly n long. That is the difference from chunks: windows overlap and are never short; chunks do not overlap and the last one may be.

Its job is compare each element with its neighbour: differences between consecutive readings, windows(2).map(|w| w[1] - w[0]); is-it-sorted, windows(2).all(|w| w[0] <= w[1]) (which std also spells is_sorted); the longest run of equal values.

A window larger than the slice yields nothing — not an error, an empty iterator. windows(0) panics: window size must be non-zero.

Example

slice_windows.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];
    for w in v.windows(2) {
        print!("{w:?} ");
    }
    println!();
    println!("{} windows of 2 from {} elements", v.windows(2).len(), v.len());

    // Neighbour differences: the job windows exists for.
    let temps = [20, 23, 21, 25];
    let deltas: Vec<i32> = temps.windows(2).map(|w| w[1] - w[0]).collect();
    println!("{deltas:?}");

    // Sorted? Every neighbouring pair in order.
    println!("{} {}", v.windows(2).all(|w| w[0] <= w[1]), temps.windows(2).all(|w| w[0] <= w[1]));

    // A window larger than the slice yields nothing, silently.
    println!("{}", v.windows(9).count());

    // windows overlap; chunks do not.
    println!("{:?}", v.chunks(2).collect::<Vec<_>>());

    // 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.windows(0).count());
    std::panic::set_hook(hook);
    println!("windows(0) panicked: {}", r.is_err());
}

Verified output of slice_windows.rs — regenerated by tools/run_examples.py, never hand-typed.

[1, 2] [2, 3] [3, 4] 
3 windows of 2 from 4 elements
[3, -2, 4]
true false
0
[[1, 2], [3, 4]]
windows(0) panicked: true

See also

slice::windows in the standard library ↗