typestar

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

  1. A producer sends and then closes the channel.
  2. <-chan int is a receive-only channel type.
  3. range over a channel ends when it closes.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 4 in Channels, step 6 of 25 in Concurrency.

← Previous Next →

Channels in other languages