Rust Snippets #0 - The Windows Function

Rust Snippets #0 - The Windows Function

This is the first in an ongoing log of easy/simple/esoteric methods, functions and patterns in Rust that will (hopefully) make your life easier. I'm writing it in parallel to a similar series in Python, the first post of which you can find here.

This article is all about the windows function in Rust. I can see it being useful in a myriad of circumstances but for the sake of easily explaining what it does, we're just going to demonstrate its functionality with a simple character array.

fn main() {

    let arr = ['v','a','l','h','a','l','l','a'];
    for window in arr.windows(2){
        println!("[{},{}]", window[0], window[1]);
    }
}
Output:
[v,a]
[a,l]
[l,h]
[h,a]
[a,l]
[l,l]
[l,a]

What the windows function does is creates an iterator over a slice array of size n windows and, in this case, prints out both members of the window. So the first window is the first and second letter, the second window is the second and third window, then the third and fourth... etc.

Notably, you're going to get repeated letters here, but it is useful for problems like finding specific substrings in a long string of text, parsing structured filetypes, etc. I definitely could have used it in Advent of Code...