Statement

Range over iterator functions

From Go 1.23, range accepts iterator functions taking a yield callback that returns bool and accepts zero, one or two iteration values. The iterator must not call yield again after false. Example output: '1\n2'.

Formal Syntax & Structure

go syntaxgo
for value := range iterator { ... }

Working Example

Example Snippetgo
package main
import "fmt"
func seq(yield func(int) bool) {  for n := 1; n <= 3; n++ {    if !yield(n) {      return    }  }}func main() {  for n := range seq {    fmt.Println(n)    if n == 2 {      break    }  }}
Go Reference