typestar

Range over function in Go

Go 1.23 lets a function be ranged over, which is how iterators work now.

func Countdown(from int) iter.Seq[int] {
    return func(yield func(int) bool) {
        for n := from; n > 0; n-- {
            if !yield(n) {
                return
            }
        }
    }
}

func Enumerate[T any](values []T) iter.Seq2[int, T] {
    return func(yield func(int, T) bool) {
        for i, value := range values {
            if !yield(i, value) {
                return
            }
        }
    }
}

func use() (int, string) {
    sum := 0
    for n := range Countdown(4) {
        sum += n
    }

    var last string
    for _, value := range Enumerate([]string{"a", "b"}) {
        last = value
    }
    return sum, last
}

How it works

  1. An iterator is a func taking a yield callback.
  2. Returning false from yield stops the iteration.
  3. iter.Seq and iter.Seq2 name the two shapes.

Keywords and builtins used here

The run, in numbers

Lines
32
Characters to type
479
Tokens
160
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 2 of 2 in API shapes, step 18 of 19 in Interfaces & generics.

← Previous Next →