Go 1.27 reference · Slices, Maps, Iterators and JSON

Go iter.Seq (range over functions) Type

Write iterators as functions that yield values, and loop over them with for range like slices and maps.

Go 1.27 Since 1.23

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

type Seq[V any] func(yield func(V) bool)   type Seq2[K, V any] func(yield func(K, V) bool)

Parameters

ParameterDescription
yield(v) Produce a value; returns false when the loop stopped early.
for v := range seq Consume the iterator.

Examples

Example 1
package main

import (
	"fmt"
	"iter"
)

func evens(limit int) iter.Seq[int] {
	return func(yield func(int) bool) {
		for i := 0; i < limit; i += 2 {
			if !yield(i) {
				return
			}
		}
	}
}

func main() {
	for n := range evens(10) {
		fmt.Print(n, " ")
	}
	fmt.Println()
}

Output

0 2 4 6 8 

Run this on your computer — see “Get Started” for setup.

Two values and stopping early
package main

import (
	"fmt"
	"iter"
)

func numbered(lines []string) iter.Seq2[int, string] {
	return func(yield func(int, string) bool) {
		for i, l := range lines {
			if !yield(i+1, l) {
				return
			}
		}
	}
}

func main() {
	for i, line := range numbered([]string{"alpha", "beta", "gamma"}) {
		if i == 2 {
			break // stops the iterator early
		}
		fmt.Println(i, line)
	}
}

Output

1 alpha

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Go 1.23Added

Was this page helpful?