Channel directions
Context
Section titled “Context”When using channels as function parameters, you can specify direction: chan<- T (send‑only) or <-chan T (receive‑only). This improves type safety.
Example
Section titled “Example”Pass a send‑only channel to a producer and a receive‑only channel to a consumer.
Code example
Section titled “Code example”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)}Output
Section titled “Output”012