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.
Code
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
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 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.