Skip to content

Channel directions

When using channels as function parameters, you can specify direction: chan<- T (send‑only) or <-chan T (receive‑only). This improves type safety.

Pass a send‑only channel to a producer and a receive‑only channel to a consumer.

package main
import "fmt"
func producer(out chan<- int) {
for i := 0; i < 3; i++ {
out <- i
}
close(out)
}
func consumer(in <-chan int) {
for v := range in {
fmt.Println(v)
}
}
func main() {
ch := make(chan int)
go producer(ch)
consumer(ch)
}
Terminal window
0
1
2