slices.Values And Collect Bridge Seqs
Convert slices to iter.Seq with slices.Values and rebuild with slices.Collect, so consumers can accept any iterator without caring about storage.
Code
package main
import (
"fmt"
"iter"
"slices"
)
// 消费端只认 iter.Seq:不关心数据来自切片、map 还是网络
func summarize(seq iter.Seq[int]) (count, total int) {
for v := range seq {
count++
total += v
}
return count, total
}
func main() {
xs := []int{4, 8, 15, 16}
// slices.Values 把切片升级成 iter.Seq
seq := slices.Values(xs)
count, total := summarize(seq)
fmt.Println("count:", count, "total:", total)
// slices.Collect 反向操作:把任意 iter.Seq 收回切片
ys := slices.Collect(slices.Values(xs))
fmt.Println("rebuilt:", ys)
}How the file behaves
slices.Values And Collect Bridge Seqs reduces to the functions summarize and main.
Iteration happens inside for v := range seq — everything outside it runs once.
Caveats
- Self-contained — no imports beyond what the runtime itself provides.
Using it
Signature: func summarize(seq iter.Seq[int]) (count, total int)
The demo output is labeled (count:, rebuilt:), so every line of output points back to the operation behind it.
Running the file executes main, which drives summarize in order.
Key statements
func summarize(seq iter.Seq[int]) (count, total int) {
for v := range seq {
count++
total += v
}
return count, total
}
func main() {
xs := []int{4, 8, 15, 16}
// slices.Values 把切片升级成 iter.Seq
seq := slices.Values(xs)
count, total := summarize(seq)
fmt.Println("count:", count, "total:", total)
// slices.Collect 反向操作:把任意 iter.Seq 收回切片
ys := slices.Collect(slices.Values(xs))
fmt.Println("rebuilt:", ys)
}
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.Values And Collect Bridge Seqs print when run?
- Run it as a complete program — the output lines carry labels such as `count:`, `rebuilt:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.