← 中文资源

简体中文版本

AppendSeq 把序列排入切片

slices.AppendSeq 把 iter.Seq 里的元素逐个追加进已有切片并复用原底层数组,比先 Collect 出新切片再拼接少一次分配。

阅读英文原文

实现说明

全部逻辑都在函数 page、main中。 文件的主干是一个循环——for _, rec := range []int{11, 22, 33}。

使用要点

  • 直接运行文件,输出会带上标签,比如 appended:、from nil:——输出的每一行都能指回产生它的那次调用。
  • 执行文件,main 会按顺序走完 page。

常见问题

运行「AppendSeq 把序列排入切片」会打印什么?

运行文件本身,appended:、from nil: 这些前缀各对应一段演示逻辑。

主要签名是 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)
}

代码示例

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)
}