Channel direction in Go
A parameter type can restrict a channel to sending or receiving.
func produce(out chan<- int, count int) {
for i := 1; i <= count; i++ {
out <- i * i
}
close(out)
}
func consume(in <-chan int) int {
total := 0
for value := range in {
total += value
}
return total
}
func pipeline() int {
numbers := make(chan int)
go produce(numbers, 4)
return consume(numbers)
}
How it works
chan<- Tonly sends,<-chan Tonly receives.- The compiler enforces it, so a producer cannot read its own output.
- Only the sender should close, which the types make obvious.
Keywords and builtins used here
chancloseforfuncgointmakerangereturn
The run, in numbers
- Lines
- 20
- Characters to type
- 299
- Tokens
- 87
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 52 seconds.
Step 4 of 4 in Channels, step 7 of 25 in Concurrency.