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.

GoData Integrity

Code

gosnippet
29 lines
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

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:`.