Channel directions
A channel type can be restricted to send-only (chan<- T) or receive-only (<-chan T). The restriction is checked at compile time and documents which side of the pipe a function owns.
Detailed Explanation
func produce() <-chan int returns a channel the caller can only receive from. func consume(ch <-chan int) cannot close or send. func send(ch chan<- int) cannot receive. The underlying channel is still bidirectional; the type of the variable is narrower.
Why bother. A bidirectional chan T in an API lets a confused caller close the channel the producer still uses, or send on a channel that was meant to be read-only. Directional types make that a compile error. They also read as a contract: this function produces, that one consumes.
Conversion is one way. You may assign chan T to chan<- T or <-chan T. You may not go back. There is no "cast to bidirectional." If you need both operations, keep the bidirectional name inside the owning function and hand out directed views.
Close is a send-side operation. You cannot close a <-chan T. You can close a chan<- T or chan T. That matches the rule "the sender closes."
nil still applies. A nil <-chan T blocks on receive forever. Direction does not change nil behaviour.
What it costs. Nothing at runtime — the channel is the same. The cost is a bit of syntax at function boundaries, which is cheap compared to a panic from a close on the wrong side.
Code Examples
package main
import "fmt"
func produce(n int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 0; i < n; i++ {
out <- i
}
}()
return out
}
func consume(in <-chan int) {
for v := range in {
fmt.Println(v)
}
}
func main() {
consume(produce(3))
}func onlySend(ch chan<- string, s string) {
ch <- s
// v := <-ch // compile error
}Common Gotchas
`close` on a receive-only channel does not compile
close in the producer that holds `chan T` or `chan<- T`.
Returning `chan T` from a producer lets callers close it
return `<-chan T` instead.
Direction is part of the type
`chan int` and `<-chan int` are different; you cannot store both in one slice type without a common bidirectional source.
`range` requires a receive direction
that is already `<-chan` or `chan`.