Slices And Maps As Iterator Sources
Adapt slices into iter.Seq with slices.Values, then rebuild with slices.Collect, slices.AppendSeq, and maps.Collect so consumers stay decoupled from storage.
Code
package main
import (
"fmt"
"maps"
"slices"
)
func main() {
words := []string{"auth", "billing", "cache", "auth"}
// slices.Values 把切片变成 iter.Seq:range-over-func 消费者不关心底层是什么集合
for w := range slices.Values(words) {
fmt.Println("value:", w)
}
// slices.Collect 反向:把任意 iter.Seq 收回切片
echoed := slices.Collect(slices.Values(words))
fmt.Println("collected:", echoed)
// slices.AppendSeq 从 seq 增量构建切片,可携带已有前缀
prefixed := slices.AppendSeq([]string{"start"}, slices.Values(words))
fmt.Println("appended:", prefixed)
// maps.All 产出 iter.Seq2;maps.Collect 再从 seq2 重建 map
retries := map[string]int{"orders": 3, "billing": 1}
cloned := maps.Collect(maps.All(retries))
cloned["orders"] = 9
fmt.Println("original:", retries["orders"], "clone:", cloned["orders"])
}What the code does
The moving parts are the function main.
The one repetition in this snippet is the loop for w := range slices.Values(words).
Points of care
- No install step: all APIs used ship with the platform.
Applying it
Declared as func main()
Look for the value:, collected:, appended: prefixes when the file runs; they tie each line to its step.
The statements worth quoting
for w := range slices.Values(words) {
fmt.Println("value:", w)
}
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 Slices And Maps As Iterator Sources print when run?
- Execute the whole file; each printed line is prefixed with a label like `value:`, `collected:`, `appended:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.