Range Over Iterator Functions With Iter.Seq
Consume iter.Seq iterators with range: maps.Keys streams keys on demand, slices.Sorted materializes them ordered, and custom yield functions stop on break.
Code
package main
import (
"fmt"
"iter"
"maps"
"slices"
)
// countdown 返回 iter.Seq[int]:一个可被 range 的迭代器函数
func countdown(from int) iter.Seq[int] {
return func(yield func(int) bool) {
for v := from; v > 0; v-- {
if !yield(v) {
return // 调用方 break 时提前终止
}
}
}
}
func main() {
settings := map[string]int{"retries": 3, "timeout": 30, "batch": 100}
// 标准库迭代器:maps.Keys 逐个产出键(顺序随机)
for name := range maps.Keys(settings) {
fmt.Println("has key:", name)
}
// slices.Sorted 把迭代器物化成有序切片,输出确定
fmt.Println("sorted keys:", slices.Sorted(maps.Keys(settings)))
// 自定义迭代器与任何序列一样被 range 消费
for v := range countdown(3) {
fmt.Println("countdown:", v)
}
}What the code does
Count the functions countdown and main as the entire surface area of Range Over Iterator Functions With Iter.Seq.
The cycling part of this snippet is for v := from; v > 0; v--.
Applying it
Entry signature: func countdown(from int) iter.Seq[int]
The demo output is labeled (has key:, sorted keys:, countdown:), so every line in the printed output names the step that produced it.
Execute the file and main walks through countdown, in that order.
Statements that carry the weight
return func(yield func(int) bool) {
for v := from; v > 0; v-- {
if !yield(v) {
return // 调用方 break 时提前终止
}
}
}
for name := range maps.Keys(settings) {
fmt.Println("has key:", name)
}
for v := range countdown(3) {
fmt.Println("countdown:", v)
}
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.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.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 Range Over Iterator Functions With Iter.Seq print when run?
- No setup needed: run the file and look for labeled lines like `has key:`, `sorted keys:`, `countdown:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.