Go Channel

As the name suggests, a Channel in Go language is an abstract type using which we can send and receive values.

Go Channels by default, send and receive operations block until the other side (channel) is ready. Using this behaviour, we can send values into channels from one goroutine and receive those values into another goroutine.

Create a Channel

To create a channel, use the following syntax.

mychannel := make(chan valtype)

where make and chan are keywords and valtype is the datatype of the values that are sent and received in the channel. make(chan valtype) returns a reference to the channel using which you can send and receive values.

For example, the following golang statement creates a channel named numbers which allows values of type int.

numbers := make(chan int)
ADVERTISEMENT

Send values to a Channel

To send values to a Channel, use the following syntax.

mychannel <- myvalue

where myvalue is sent to the channel mychannel. The datatype of the value should match the type used while creating the channel.

Receive values from a Channel

To receive values from the Golang Channel, use the following syntax.

myvalue := <- mychannel

where <- mychannel pops the value from mychannel and := assigns the value to myvalue. The datatype of the value should match the type used while creating the channel.

Example of a Channel with concurrent Goroutines

In the following example, we will compute the sum of numbers in an array. We split the array among two goroutines and find the sum of the two array slices concurrently. After finding sum of the slices, we write the values to channel. In the main goroutine, we will receive the value from the channel and find the complete sum.

example.go

package main

import "fmt"

func sum(s []int, mychannel chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
	mychannel <- sum // send sum to channel
}

func main() {
	s := []int{7, -2, 8, 9, 4, 5, 1, 6}

	mychannel := make(chan int)
	go sum(s[:len(s)/2], mychannel)
	go sum(s[len(s)/2:], mychannel)
	x := <-mychannel // receive from mychannel
	y := <-mychannel // receive from mychannel

	fmt.Println("Sum computed in first goroutine: ", x)
	fmt.Println("Sum computed in second goroutine: ", y)
	fmt.Println("Total sum: ", x+y)
}

Output

Sum computed in first goroutine:  16
Sum computed in second goroutine:  22
Total sum:  38

Get Number of Elements in Golang Channel

To get the number of elements queued in Golang Channel buffer, you can use len() function. Pass channel as argument to len() function and len() function shall return you the number of elements in the channel.

Conclusion

In this Golang Tutorial, we learned about Channels in Go programming language.