slices.All Yields Index And Value Pairs

slices.All yields index and value pairs as iter.Seq2, so a full pass over a slice can be handed to any function that consumes pairs.

GoData Integrity

Code

gosnippet
31 lines
package main

import (
	"fmt"
	"iter"
	"slices"
)

// collectPairs 消费任意 iter.Seq2[int, string]:slices.All 的产出正好匹配
func collectPairs(pairs iter.Seq2[int, string]) []string {
	var out []string
	for index, value := range pairs {
		out = append(out, fmt.Sprintf("%d:%s", index, value))
	}
	return out
}

func main() {
	pipeline := []string{"build", "test", "deploy"}

	// slices.All yields index and value pairs:不必手写 i, v 循环即可整段交出
	formatted := collectPairs(slices.All(pipeline))
	fmt.Println("pairs:", formatted)

	// 迭代器是惰性的:同一份 All 结果可以再次 range
	total := 0
	for index := range slices.All(pipeline) {
		total += index
	}
	fmt.Println("index sum:", total, "len:", len(pipeline))
}

How it works

slices.All Yields Index And Value Pairs is built around the functions collectPairs and main.

for index, value := range pairs is the loop that carries the per-item work.

Using it

The entry-point signature is func collectPairs(pairs iter.Seq2[int, string]) []string

The demo output is labeled (pairs:, index sum:); each label names the call that printed it.

The entry point wires collectPairs together — run it once and the whole demo flows.

Key statements

out = append(out, fmt.Sprintf("%d:%s", index, value))
for index := range slices.All(pipeline) {
	total += index
}

Interactive Tools for This Topic

FAQ

What does slices.All Yields Index And Value Pairs print when run?
The script runs standalone; its 2 labeled outputs include `pairs:`, `index sum:`.