Knaph

Select

select: waiting on multiple channels

select looks like switch, but each case is a channel operation, and it picks whichever one is ready first:

select {
case v := <-ch1:
	fmt.Println("from ch1:", v)
case v := <-ch2:
	fmt.Println("from ch2:", v)
default:
	fmt.Println("neither ready")
}

Without a default case, select blocks until one of the channel operations can proceed. With one, it returns immediately if nothing's ready — the non-blocking check. This is the tool for the common case of "wait for whichever of these several things finishes first" — for instance, a result channel and a timeout channel (time.After) raced against each other, so a slow operation doesn't hang your program forever.

Goroutines, channels, buffering, and select are the whole toolkit. Nearly everything you'll see in real concurrent Go code, including the concurrency chapters of this site's Operating Systems course, is built by combining them.

Sign in to track your progress through this course.

Ask an AI

Open a ready-made prompt in ChatGPT or Claude — just press Enter.

SummarizeChatGPTClaude
Ask me questionsChatGPTClaude
Let's learn togetherChatGPTClaude