Channel Directionality
This lesson discusses different patterns for the implementation of channels for communication between goroutines.
We'll cover the following...
A channel type may be annotated to specify that it may only send or only receive data:
var send_only chan<- int // data can only be sent (written) to the channel
var recv_only <-chan int // data can only be received (read) from the channel
Receive-only channels (<-chan T
) cannot be closed, because closing a channel is intended as a way for a sender goroutine to signal that no more values will be sent to the channel. Therefore, it has no meaning for receive-only channels. All channels are created bidirectional, but we can assign them to directional channel variables, like in this code snippet:
var c = make(chan int) // bidirectional
go source(c)
go sink(c)
func source(ch chan<- int) {
for { ch <- 1 } // sending data to ch channel
}
func sink(ch <-chan int) {
for { <-ch } // receiving data from ch channel
}
Channel iterator pattern
This pattern can be applied in the common case where we have to populate a channel with the items of a container type, which ...