Rust’s slice::windows is really cool

Austin Tindle
1 min readJun 16, 2019
Photo by Zsolt Palatinus on Unsplash

This post is one of several that outline my perspective on learning Rust as someone who primarily uses JavaScript. You can find the rest here.

Rust has a lot of powerful features associated with its primitives and standard library. A cool one I just came across is the method slice::windows. This method returns an iterator over a slice. The iterator length can be specified. It lets you iterate over a slice and have a window of a specific size on each pass. For example:

// windows.rslet slice = ['w', 'i', 'n', 'd', 'o', 'w', 's'];for window in {
&println!{"[{}, {}]", window[0], window[1]};
// prints: [w, i] -> [i, n] -> [n, d] -> [d, o] -> [o, w] -> [w, s]

This is pretty cool, and doesn’t really have a parallel in JavaScript. The closest that I can come up with to achieve the same is this:

// windows.jslet slice = ["w", "i", "n", "d", "o", "w", "s"];slice.forEach((char, index) => {
if (index === slice.length - 1) return;
console.log(`[${slice[index]}, ${slice[index + 1]}]`);

The JavaScript approach is definitely less ergonomic, and I really like the concept of windows as an abstraction for use with iterators.

Thanks for reading.

Austin Tindle

Software developer, writer, sometimes thinker | Engineering manager @ |