Channel Direction and Pipeline Patterns
Read-only, write-only channels and pipelines
Directional Channel Types
Go lets you restrict channels to send-only or receive-only in type signatures. This documents intent and prevents misuse:
package main
// send-only: can only send, not receive or close (close is allowed by sender)
func sender(out chan<- int) {
out <- 42
}
// receive-only: can only receive, not send or close
func receiver(in <-chan int) int {
return <-in
}
// bidirectional: can do both
func relay(in <-chan int, out chan<- int) {
out <- <-in
}Converting Channel Directions
A bidirectional channel can be implicitly converted to either directional type, but not the reverse:
package main
import "fmt"
func produce(out chan<- int) { out <- 1; close(out) }
func consume(in <-chan int) { fmt.Println(<-in) }
func main() {
ch := make(chan int) // bidirectional
go produce(ch) // auto-converts to chan<- int
consume(ch) // auto-converts to <-chan int
// chan<- int cannot be converted back to <-chan int
}All lessons in this course
- Launching Goroutines
- Unbuffered Channels
- Buffered Channels
- Channel Direction and Pipeline Patterns