~/Golang Channel Direction Explained

Mar 13, 2020


Golang channels support direction to enforce if a function can only send or receive values. This increases code safety and clarity.

Direction Types

chan T means send and receive permitted.
chan<- T means send only.
<-chan T means receive only.

Example Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
func send(ch chan<- int, val int) {
    ch <- val // Only sending is allowed
}

func receive(ch <-chan int) int {
    return <-ch // Only receiving is allowed
}

func main() {
    ch := make(chan int)
    go send(ch, 10)
    val := receive(ch)
    fmt.Println(val)
}

Passing directional channels prevents misuse. For more, see Golang Tour: Channels and Go Spec.

Tags: [golang]