Better Programming

Advice for programmers.

Follow publication

Member-only story

When and How to Use the Go Channel

Stefanie Lai
Better Programming
Published in
8 min readAug 26, 2022
Source: unsplash, @bdv91

Go’s concise structure and powerful native library enable us to hit the ground running easily. It is more efficient than Java or Python when implementing the same functions, especially its concurrent programming, which is very handy and widely admired due to its goroutine and channel.

goroutine and channel has much to dig into, and let’s start with channel, which I used to consider narrowly as a message queue to transfer data between goroutines and support data synchronization, but definitely owns a bigger stage.

Channel == Semaphore + Buffer

Channel is a data type like slice and map, and the equation channel == Semaphore + Buffer reveals its essence. Semaphore is the core concept followed by the two major features, delivery guarantee, and state.

Delivery guarantee clears the way for goroutine, saving it from focusing on whether the signal can be transferred through the channel or whether the dependent channel can receive the signal but only on the logic implementation. In the example below, the delivery guarantee of ch1 and ch2 determines the success of the goroutine.

go func() {
for {
i,ok := <-ch1 // blocked if ch1 is empty
if ok {
ch2 <- i*i
} else {…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Write a response