typestar

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

  1. chan<- T only sends, <-chan T only receives.
  2. The compiler enforces it, so a producer cannot read its own output.
  3. Only the sender should close, which the types make obvious.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Channels, step 7 of 25 in Concurrency.

← Previous Next →