Need to look at consecutive pairs (or triples) in a slice? Stop manually indexing — array_windows gives you fixed-size windows as arrays, not slices.
1
2
3
4
5
6
7
8
9
10
11
12
13
| let temps = [18.0, 21.5, 19.0, 23.0, 22.5];
// Before: manual indexing 😬
for i in 0..temps.len() - 1 {
let diff = temps[i + 1] - temps[i];
println!("Δ {diff:+.1}");
}
// After: array_windows ✨
for [prev, next] in temps.array_windows() {
let diff = next - prev;
println!("Δ {diff:+.1}");
}
|
Stabilized in Rust 1.94, array_windows works like .windows(n) but the window size is a const generic — so you get &[T; N] instead of &[T]. That means you can destructure directly in the pattern.
It’s great for detecting trends, computing deltas, or validating sequences:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| let readings = [3, 7, 2, 9, 1, 8];
let all_increasing = readings
.array_windows()
.all(|[a, b]| b > a);
assert!(!all_increasing);
// Works with triples too
let has_valley = readings
.array_windows()
.any(|[a, b, c]| b < a && b < c);
assert!(has_valley); // 2 is a valley between 7 and 9
|
No bounds checks, no .try_into().unwrap() dance. Just clean pattern matching on fixed-size windows.