Channel Directions
Restrict channels to send-only or receive-only in function signatures to document and enforce data flow.
A channel parameter can be restricted to one direction. chan<- T permits sending, and <-chan T permits receiving. The compiler rejects operations outside that direction.
The relay can read from in and send to out, but it cannot use either channel in the opposite direction.
package main
import "fmt"
func relay(in <-chan int, out chan<- int) {
value := <-in
out <- value
}
func main() {
in := make(chan int, 1)
out := make(chan int, 1)
in <- 42
relay(in, out)
fmt.Println(<-out)
}In production
Use directional types in function signatures to make data flow clear and prevent operations the function does not need. A receive-only channel cannot be sent to or closed, while a send-only channel cannot be received from. A bidirectional channel created with make(chan T) can be passed where either directional type is expected.
Enjoyed this? Get more software craft delivered to your inbox.