Send-only and receive-only channels
- Version
- 1.27
- Review
- Draft
Summary#
chan<- T allows sending, and <-chan T allows receiving. A bidirectional chan T can be passed to a parameter of either directional type, so the compiler can enforce how the function uses it.
Syntax#
func produce(out chan<- int)
func format(in <-chan int) <-chan string
Example#
package main
import "fmt"
func produce(out chan<- int, count int) {
defer close(out) // the sending side closes
for i := range count {
out <- i + 1
}
}
func ticketNames(in <-chan int) <-chan string {
out := make(chan string)
go func() {
defer close(out)
for number := range in {
out <- fmt.Sprintf("ticket-%03d", number)
}
}()
return out
}
func main() {
numbers := make(chan int) // bidirectional here
go produce(numbers, 3)
for name := range ticketNames(numbers) {
fmt.Println(name)
}
}
Expected output#
ticket-001
ticket-002
ticket-003
Common mistakes#
Closing a receive-only channel does not compile, and a directional channel cannot be converted back to a bidirectional one. In a pipeline, a consumer that stops early can leave senders blocked. Give long-running stages a cancellation signal such as a context.
Version applicability#
Channel directions work this way in Go 1.27 and earlier Go versions. The example uses ranging over an integer, which requires Go 1.22 or later.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0