iter.Pull2 Push Pull Key Values
Convert a Seq2 into next/stop functions with iter.Pull2 so the consumer pulls key-value pairs on demand instead of being driven by the producer.
Code
package main
import (
"fmt"
"iter"
"maps"
)
func main() {
quota := map[string]int{"alpha": 1, "beta": 2, "gamma": 3}
// Pull2 把 iter.Seq2(推送式)变成 (next, stop) 拉取式函数对:
// next 每次返回 (key, value, true),耗尽后返回零值与 false
next, stop := iter.Pull2(maps.All(quota))
defer stop() // 提前放弃时必须 stop,释放底层迭代状态
for {
key, value, ok := next()
if !ok {
break
}
fmt.Println("pulled:", key, value)
}
// next 耗尽后再调用仍返回 false:可安全多拉
k, v, ok := next()
fmt.Println("after exhaustion:", k, v, ok)
// 拉取式的价值:消费者决定读几个就停,不需要改造生产者
next2, stop2 := iter.Pull2(maps.All(quota))
defer stop2()
first, fval, _ := next2()
fmt.Println("only the first pair:", first, fval)
}How it works
Everything happens inside the function main.
A single loop drives the file — for. Cleanup is attached with defer, so it runs on every exit path of the function.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
The entry point every pull sequence flows through is func main()
Each phase prints its own tag (pulled:, after exhaustion:, only the first pair:), tracing the pull sequence from start to stop.
Key statements
defer stop() // 提前放弃时必须 stop,释放底层迭代状态
defer stop2()
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
- What does iter.Pull2 Push Pull Key Values print when run?
- Running the file directly is enough — expect labeled output lines such as `pulled:`, `after exhaustion:`, `only the first pair:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.