Custom iter.Seq2 Yields Pairs

Write an iter.Seq2 function yielding line-number and text pairs so range-over-func consumers can break out and stop the iterator.

GoData Integrity

Code

gosnippet
40 lines
package main

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

// lines is a custom iterator: yields (lineNumber, line) pairs; break stops it early
func lines(text string) iter.Seq2[int, string] {
	return func(yield func(int, string) bool) {
		number := 0
		for len(text) > 0 {
			line, rest, found := strings.Cut(text, "\n")
			if !yield(number, line) {
				return
			}
			number++
			if !found {
				return
			}
			text = rest
		}
	}
}

func main() {
	log := "boot ok\nconfig loaded\nready"
	for number, line := range lines(log) {
		fmt.Printf("%d: %s\n", number, line)
	}

	// break 只消费到匹配行为止,迭代器随之中止
	for number, line := range lines(log) {
		if strings.Contains(line, "config") {
			fmt.Println("found at", number)
			break
		}
	}
}

What the code does

What another module actually calls is the functions lines and main — everything else is wiring.

for len(text) > 0 is the loop that carries the per-item work.

Watch out for

  • The dependency list is empty — the language runtime already provides everything.

Applying it

The signature you will reach for first is func lines(text string) iter.Seq2[int, string]

Output lines are prefixed (found at), making the effect of each step easy to see.

The demo flow inside main is lines — run the file to see it end to end.

Statements that matter most here

for number, line := range lines(log) {
	fmt.Printf("%d: %s\n", number, line)
}
for number, line := range lines(log) {
	if strings.Contains(line, "config") {
		fmt.Println("found at", number)
		break
	}
}

Interactive Tools for This Topic

FAQ

What does Custom iter.Seq2 Yields Pairs print when run?
The script runs standalone; its 1 labeled outputs include `found at`.