实现说明
全部逻辑都在函数 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)
}