channel
# channel
Channel 在 goroutine 之间传递值。无缓冲 Channel 需要发送和接收同步会合,缓冲 Channel 允许有限数量的值暂存。
results := make(chan string, len(targets))
go func() {
defer close(results)
for _, target := range targets {
results <- check(target)
}
}()
for result := range results {
fmt.Println(result)
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
通常由发送方关闭 Channel,因为发送方知道何时不再产生数据。向已关闭 Channel 发送会 panic;Channel 不需要为了垃圾回收而关闭。缓冲区应表达容量策略,不能掩盖生命周期问题。