Channel Directionality
Explore the concept of channel directionality in Go, focusing on how to enforce send-only and receive-only operations with channels. Understand patterns like channel iterators and pipe and filter, enabling safe and efficient communication between goroutines. This lesson helps you write clearer concurrent code by restricting channel use and managing data flow in Go applications.
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 ...