Pull Iterator Pairs Two Sequences

iter.Pull converts a push-style Seq into next and stop functions, so two generators can be advanced in lockstep inside one plain loop.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"iter"
)

// push 风格迭代器:只能被 range 或 Pull 消费
func letters(seq string) iter.Seq[string] {
	return func(yield func(string) bool) {
		for _, r := range seq {
			if !yield(string(r)) {
				return
			}
		}
	}
}

func main() {
	nextWord, stopWord := iter.Pull(letters("golang"))
	defer stopWord()
	nextDigit, stopDigit := iter.Pull(letters("12345"))
	defer stopDigit()

	// Pull 之后的 next 才能手动步进:两个序列逐位配对
	for {
		word, okW := nextWord()
		digit, okD := nextDigit()
		if !okW || !okD {
			break
		}
		fmt.Println(word, digit)
	}
}

How it works

Pull Iterator Pairs Two Sequences keeps everything in the functions letters and main.

Iteration happens inside for _, r := range seq — everything outside it runs once. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Putting it to use

The surface you program against: func letters(seq string) iter.Seq[string]

The entry point wires letters together — run it once and the whole demo flows.

Core lines under the microscope

return func(yield func(string) bool) {
	for _, r := range seq {
		if !yield(string(r)) {
			return
		}
	}
}
defer stopDigit()
defer stopWord()

Interactive Tools for This Topic

FAQ

How do you run Pull Iterator Pairs Two Sequences?
The runtime alone is enough: execute the file as a complete program.