AppendSeq Drains A Sequence Into A Slice

Extend an existing slice from an iter.Seq with slices.AppendSeq, appending into the same backing storage instead of allocating.

GoData Integrity

Code

gosnippet
29 lines
package main

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

// page yields records the way a paginated source would hand them over
func page() iter.Seq[int] {
	return func(yield func(int) bool) {
		for _, rec := range []int{11, 22, 33} {
			if !yield(rec) {
				return
			}
		}
	}
}

func main() {
	// AppendSeq drains the sequence into the existing slice's storage
	buf := []int{7}
	buf = slices.AppendSeq(buf, page())
	fmt.Println("appended:", buf)

	// starting from nil, AppendSeq behaves like slices.Collect
	fromNil := slices.AppendSeq(nil, page())
	fmt.Println("from nil:", fromNil)
}

Reading the code

The quick sketch: the file hands everything to the functions page and main, doing all the work.

The loop for _, rec := range []int{11, 22, 33} is the only repeated construct.

Applying it

Entry signature: func page() iter.Seq[int]

Output lines are prefixed (appended:, from nil:), which keeps the path from step to output line readable.

Treat main as the orchestrator calling page in a fixed order.

Statements that matter

return func(yield func(int) bool) {
	for _, rec := range []int{11, 22, 33} {
		if !yield(rec) {
			return
		}
	}
}
func main() {
	// AppendSeq drains the sequence into the existing slice's storage
	buf := []int{7}
	buf = slices.AppendSeq(buf, page())
	fmt.Println("appended:", buf)
	// starting from nil, AppendSeq behaves like slices.Collect
	fromNil := slices.AppendSeq(nil, page())
	fmt.Println("from nil:", fromNil)
}

Interactive Tools for This Topic

FAQ

What does AppendSeq Drains A Sequence Into A Slice print when run?
Invoke the file as-is — the `appended:`, `from nil:` prefixes identify which step printed each line.