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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Pull Iterator Pairs Two Sequences?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.