This article describes an experimental extension to the Go language: range over func. The design of Go iterators is evolving, and this tutorial is a w

Iterators in Go — Bitfield Consulting

submited by
Style Pass
2024-06-30 10:30:03

This article describes an experimental extension to the Go language: range over func. The design of Go iterators is evolving, and this tutorial is a work in progress, so don’t forget to check back later for the latest developments.

A Golang iterator is a function that “yields” one result at a time, instead of computing a whole set of results and returning them all at once. When you write a for loop where the range expression is an iterator, the loop will be executed once for each value returned by the iterator.

That sounds complicated, but it’s actually very simple. It’s like a short-order cook who makes a dish for each customer on demand, as they come in, rather than cooking a whole day’s worth of meals in advance.

As you know, you can use range to loop over a bunch of different kinds of thing in Go: slices, maps, strings, channels. The most common case is probably looping over a slice.

But there are some disadvantages to this way of doing it. First, we have to wait until the whole slice has been generated before we can start to process the first element of it.

Leave a Comment