Welcome To Golang By Example

Channel Direction in Go (Golang)

Overview

It is possible to create bidirectional as well as uni-directional channels in golang. A channel can be created to which we can only send data, as well as a channel, can be created from which we can only receive data. This is determined by the direction of the arrow of the channel. The direction of the arrow for a channel specifies the direction of flow of data

 A channel to which we can only send data. 

This is the syntax for  such a channel

chan<- int

A channel from which we can only send data

This is the syntax for such a channel

<-chan int

Now the question is, why would you want to create a channel through to which you can only send data or from which we can only receive data.  This comes in handy while passing the channel to a function where we want to restrict the  function too either  send the data or receiver rate

There are many ways in which a channel can be passed as a function argument.

Only Send to Channel

func process(ch chan<- int){ //doSomething }
invalid operation: <-ch (receive from send-only type chan<- int)

Try uncommenting below line in the code to see the above error

s := <-ch

Code:

package main
import "fmt"
func main() {
    ch := make(chan int, 3)
    process(ch)
    fmt.Println(<-ch)
}
func process(ch chan<- int) {
    ch <- 2
    //s := <-ch
}

Output: 2

Only Receive from Channel

func process(ch <-chan int){ //doSomething }
invalid operation: ch <- 2 (send to receive-only type <-chan int)

Try uncommenting below line in the code to see the above error

ch <- 2

Code:

package main

import "fmt"

func main() {
    ch := make(chan int, 3)
    ch <- 2
    process(ch)
    fmt.Println()
}

func process(ch <-chan int) {
    s := <-ch
    fmt.Println(s)
    //ch <- 2
}

Output: 2