Directional channel types
Directional channel types
Use chan T for both directions, chan<- T for send-only and <-chan T for receive-only. A bidirectional channel can be assigned to either directional type with the same element type. Direction restricts what a function can do at compile time; it does not create a separate queue. Express producer and consumer responsibilities in their signatures.
package main
import ( "fmt")
func send(out chan<- int) { out <- 12 }func receive(in <-chan int) int { return <-in }func main() { ch := make(chan int) go send(ch) fmt.Println(receive(ch))}The functions communicate through the same channel. send cannot receive from out and receive cannot send into in. Direction is a restriction, not a guarantee that the function finishes or that multiple producers are safe to close the channel.
Expected output:
12Return a read-only stream
package main
import ( "fmt")
func one() <-chan string { ch := make(chan string, 1); ch <- "ready"; close(ch); return ch }func main() { fmt.Println(<-one())}The creator sends and closes before returning a receive-only view. A caller cannot close a receive-only channel. A send-only channel can be closed, but the ownership protocol must still permit it. Do not try to convert a directional channel back to a bidirectional channel.
Expected output:
readyTry it locally
Write a function deliver(out chan<- string) sending "done" and a function read(in <-chan string) returning a string. Use one channel to connect them.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Channels 03: Directional channel types
Check the lesson objective before moving on.
What operation is valid on <-chan int?
Does assigning chan int to chan<- int copy the buffer?