« Back to Index

Go: 1.23 iter.Seq/iter.Seq2 iterators

View original Gist on GitHub

Tags: #go #iterator

main.go

// This code demonstrates how iterators work in Go.
// This particular example is contrived, but I wanted something simple enough to demonstrate the point.

package main

import (
	"fmt"
	"iter"
	"strings"
)

// stringlines returns an iterator over lines in a string.
func stringlines(s string) iter.Seq[string] {
	return func(yield func(string) bool) {
		lines := strings.Split(s, "\n")
		for _, line := range lines {
			if !yield(line) { // Call yield with the current line
				return // Stop if yield returns false
			}
		}
		fmt.Println("yield() never returned false so the internal for loop kept going")
	}
}

func main() {
	data := "line one\nline two\nline three"

	// function stringlines() returns an iterator:
	for line := range stringlines(data) {
		fmt.Println(line)
	}

	// Iterating with early exit:
	// If the range 'block' returns/breaks, then that == false
	// If the range 'block' completes, then that == true
	for line := range stringlines(data) {
		fmt.Println(line)
		if line == "line two" {
			break // exits the loop, signifying to yield() it should stop the loop inside of stringlines()
		}
	}
}