Channels in Go
Typed pipes that carry values between goroutines.
func produce(n int) <-chan int {
out := make(chan int)
go func() {
defer close(out)
for i := 1; i <= n; i++ {
out <- i * i
}
}()
return out
}
func consume(in <-chan int) int {
total := 0
for v := range in {
total += v
}
return total
}
How it works
- A producer sends and then
closes the channel. <-chan intis a receive-only channel type.rangeover a channel ends when it closes.
Keywords and builtins used here
chanclosedeferforfuncgointmakerangereturn
The run, in numbers
- Lines
- 18
- Characters to type
- 235
- Tokens
- 77
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 46 seconds.
Step 3 of 4 in Channels, step 6 of 25 in Concurrency.