Go by Example

Channel Directions

Restrict channels to send-only or receive-only in function signatures to document and enforce data flow.

A channel passes values between goroutines, functions started with go that can run while their caller continues. A function can receive a channel that only allows sending or only allows receiving. chan<- T means send values of type T; <-chan T means receive them. Go reports an error if the function tries the other operation.

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 a one-way channel in a function signature to show which direction the function uses. A receive-only channel cannot send or close; a send-only channel cannot receive. A channel made with make(chan T) can both send and receive, and can be passed to either kind of function.

Enjoyed this? Get more software craft delivered to your inbox.