Pipeline Stages Close Their Outputs In Order
Each pipeline stage ranges its input and defers close on its own output, so a three-stage chain drains fully and ends without leaks.
Code
package main
import "fmt"
// gen 把切片变成 pipeline 源头:发送完毕必须关闭输出
func gen(nums []int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
out <- n
}
}()
return out
}
// square 从上游 range,处理完再关闭自己的输出:每一级 stage 都遵守同一纪律
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
out <- n * n
}
}()
return out
}
func main() {
// 上游关闭让下一级 range 结束,结束又触发下一级关闭:all stages close
// their outputs in order,三级串联完整排空且不泄漏 goroutine
for v := range square(square(gen([]int{1, 2, 3, 4}))) {
fmt.Println("stage output:", v)
}
}The shape of the run
What another module actually calls is the functions gen, square and main — everything else is wiring.
Iteration happens inside for _, n := range nums — everything outside it runs once. The goroutine/channel pair splits producer and consumer while keeping the handoff race-free. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.
Putting it to use
The definition you build on: func gen(nums []int) <-chan int
The demo output is labeled (stage output:), so each line traces straight back to the statement that printed it.
Execute the file and main walks through square and gen, in that order.
Core lines
func square(in <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for n := range in {
out <- n * n
}
}()
return out
}
func gen(nums []int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, n := range nums {
out <- n
}
}()
return out
}
for v := range square(square(gen([]int{1, 2, 3, 4}))) {
fmt.Println("stage output:", v)
}
Interactive Tools for This Topic
FAQ
- What does Pipeline Stages Close Their Outputs In Order print when run?
- Execute the whole file; each printed line is prefixed with a label like `stage output:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.