Advertisement

In the previous blog, we learned about Channels in Golang. In this blog, we will discuss the types of channels in Golang.

Learn about Golang channels from here.

Types of Golang Channels

In the previous example, we saw receiving values from the channel and sending values to the channel, this is however done in different goroutine anonymous functions, but there is no special provision that sending and receiving values to and from channels should only be done in separate functions.

We can send and receive values to and from channels in both functions.

Example

func main() {
	ch := make(chan int)
	wg.Add(2)
	go func() {
		i := <-ch
		fmt.Println("Value of Channel i =", i)
		ch <- 13
		wg.Done()
	}()
	go func() {
		var i int
		i = 17
		ch <- i
		fmt.Println("Value of ch =", <-ch)
		wg.Done()
	}()
	wg.Wait()
}

Output:

Value of Channel i = 17
Value of ch = 13

In this example we are sending and receiving value to and from channels in both the goroutine functions.

sending and receiving channels types golang
sending and receiving channel golang

The image explains the above code and how the output is received.

This is very confusing and there is a way to separate out sending and receiving channels.

1. Golang Receive only Channel function

In the function parameter section, define what kind of channel the function works with.

In this case, the function is defined with the receive-only channel.

	go func(ch <-chan int) {
		i := <-ch
		fmt.Println("Value of Channel i =", i)
		wg.Done()
	}(ch)

If the receive-only channel function tries to send value to the channel, it will give us an error.

Example:

	go func(ch <-chan int) {
		i := <-ch
		fmt.Println("Value of Channel i =", i)
                // Sending data to channel in receive only function
		ch <- 13
		wg.Done()
	}(ch)

Error:- invalid operation: ch <- 13 (send to receive-only type <-chan int)

2. Golang Send only Channel function

The send-only channel function is used to send data to the channel.

	go func(ch chan<- int) {
		var i int
		i = 17
		ch <- i
		// fmt.Println("Value of ch =", <-ch)
		wg.Done()
	}(ch)

Error is given if the send-only channel function tries to receive data from the channel.

Example:

	go func(ch chan<- int) {
		var i int
		i = 17
		ch <- i
		fmt.Println("Value of ch =", <-ch)
		wg.Done()
	}(ch)

Error:- invalid operation: <-ch (receive from send-only type chan<- int)

One thing to notice in these send only and receive only channels, the argument passed during the function call is a bi-directional channel but the function takes only a uni-directional channel. How does this happen?

The answer is the Go runtime converts the bi-direction channel to the specific requirement of the uni-directional channel.

Learn more about Channels in Golang from the official Documentation.

About Author
5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top