Nil Channel Disables Select Cases
Merge several channels and set drained ones to nil so their select cases stop firing, letting the fan-in loop finish instead of spinning on zero values.
Code
package main
import (
"fmt"
"slices"
)
// produce 把 items 逐个发给下游,发完即 close
func produce(items []int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, item := range items {
out <- item
}
}()
return out
}
// merge 汇流两个通道:耗尽后置为 nil,select 里对应分支永不就绪,
// 不会再读到关闭通道的零值
func merge(a, b <-chan int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for a != nil || b != nil {
select {
case v, ok := <-a:
if !ok {
a = nil
continue
}
out <- v
case v, ok := <-b:
if !ok {
b = nil
continue
}
out <- v
}
}
}()
return out
}
func main() {
merged := merge(produce([]int{1, 2, 3}), produce([]int{10, 20, 30}))
var got []int
for v := range merged {
got = append(got, v)
}
// 两个来源交错到达的顺序不固定,但元素一个不少、一个不重
slices.Sort(got)
fmt.Println("merged:", got)
}When each part runs
Nil Channel Disables Select Cases is built around the functions produce, merge and main.
Iteration happens inside for _, item := range items — everything outside it runs once. Work runs on a goroutine and results come back through a channel, giving a safe handoff between the two execution contexts. Deferred at entry, executed at exit: defer keeps cleanup adjacent to acquisition.
Applying it
Entry signature: func produce(items []int) <-chan int
Look for the merged: prefixes when the file runs; they tie each line to its step.
The demo flow inside main is merge and produce — run the file to see it end to end.
Statements that matter
func produce(items []int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for _, item := range items {
out <- item
}
}()
return out
}
for v := range merged {
got = append(got, v)
}
Interactive Tools for This Topic
FAQ
- What does Nil Channel Disables Select Cases print when run?
- No setup needed: run the file and look for labeled lines like `merged:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.