DEV Community

Austin Tindle
Austin Tindle

Posted on

2

Rust's `slice::windows` is really cool

Cover photo by Gordon Williams 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.rs

let slice = ['w', 'i', 'n', 'd', 'o', 'w', 's'];

for window in slice.windows(2) {
  &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.js

let 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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay