Channel Directions
By default, channels are bidirectional (you can send and receive). However, you can use directional channel types to restrict how a channel is used within a specific function.
Read-Only Channels
A read-only channel is denoted by the arrow pointing away from the chan keyword.
func processData(ch <-chan int) {
// This function can ONLY receive from ch
// ch <- 42 // This would cause a compile error
}
Write-Only Channels
A write-only channel is denoted by the arrow pointing toward the chan keyword.
func fetchData(ch chan<- int) {
// This function can ONLY send to ch
// <-ch // This would cause a compile error
}
Why use directions?
- Type Safety: The compiler ensures that a receiver doesn’t accidentally send data, or a sender doesn’t accidentally receive.
- Clear Intent: Directional types act as documentation for your functions’ behavior.
- API Contracts: You can pass a bidirectional channel to a function that only accepts a directional one; Go will handle the conversion automatically.