A simple explanation of Go channels

Robert O’Connor
2 min readMay 16, 2023

--

An analogy I like to use is that a channel is like a space portal, it requires an entry point and an exit point that both need to be open at the same time for you to pass something through.

channels are a powerful feature for communication and synchronization between goroutines. A channel is a typed conduit through which you can send and receive values with the channel operator <-.

Channels are created using the built-in make function, with a syntax like this:

ch := make(chan int)

In this example, we create a channel that can be used to communicate values of type int. Once a channel is created, it can be used to send and receive values between goroutines.

Here is an example of sending and receiving values through a channel:

func main() {
portalEntry := make(chan string)
go func() {
portalEntry <- "Morty, can you hear me?"
}()
portalExit := <-portalEntry
fmt.Println("portalExit:", portalExit)
}

In this example, we create a channel of type string and then start a new goroutine to send a message through the channel. The message is sent using the channel operator <-. Once the message is sent, the main program waits to receive a value from the channel using <-portalEntry. When the message is received, it is printed to the console like so:

portalExit: Morty, can you hear me?

Yes Rick we can hear you.

synchronize the execution of multiple goroutines

Channels can also be used to synchronize the execution of multiple goroutines. For example, you can use a channel to block a goroutine until a specific condition is met. Here is an example:

func main() {
portalEntry := make(chan bool)
go func() {
time.Sleep(time.Second)
portalEntry <- true
}()
fmt.Println("Hurry Up Morty, my portal gun is running out of juice..")
<-portalEntry
fmt.Println("Awwh Jeeze Rick, it was only a second.")
}

In this example, we create a channel of type bool and start a goroutine that sleeps for one second before sending a value through the channel. The main program waits to receive a value from the channel, effectively blocking until the goroutine is finished. Once the value is received, the program prints the final log to the console.

In summary, channels are a powerful feature of Golang that allow for communication and synchronization between goroutines. They make it easy to write concurrent programs that can communicate with each other safely and efficiently.

--

--

Robert O’Connor
Robert O’Connor

Written by Robert O’Connor

Writing about building businesses and simplifying software development. https://rob-oconnor.com

No responses yet