有時候你可能想分割來自通道的多個值,以便將它們發送到兩個獨立區域。
想像一下:你可能想要在一個通道上接收一系列操作指令,將它們發送給執行者,同時記錄操作日志。
與Unix系統的tee命令功能類似,我們用tee-channel來實現同樣的功能。你可以傳遞給它一個用作讀取的通道,它會返回兩個單獨的通道:
tee := func(
done <-chan interface{},
in <-chan interface{},
) (_, _ <-chan interface{}) { <-chan interface{}) {
out1 := make(chan interface{})
out2 := make(chan interface{})
go func() {
defer close(out1)
defer close(out2)
for val := range orDone(done, in) {
var out1, out2 = out1, out2 //1
} }
}()
select {
case <-done:
case out1 <- val:
out1 = nil //3
case out2 <- val:
out2 = nil //3
}
return out1, out2
}
這是一個快速調用示例:
done := make(chan interface{})
defer close(done)
out1, out2 := tee(done, take(done, repeat(done, 1, 2), 4))
for val1 := range out1 {
fmt.Printf("out1: %v, out2: %v\n", val1, <-out2)
}