Member-only story

What can Go language select do?

Beck Moulton
3 min readSep 7, 2023

--

In the Go language, select is a keyword used for monitoring IO operations related to channels. With the select statement, we can simultaneously monitor multiple channels and perform corresponding actions when any of the channels is ready. This article will summarize common use cases for the select statement and considerations when using it.

Basic Syntax: The basic syntax of the select statement is as follows:

select {
case <-channel1:
// Logic to handle channel1 being ready
case data := <-channel2:
// Logic to handle channel2 being ready
default:
// Default logic when no channel is ready
}

Seeing this syntax, it’s easy to think of the switch statement. Although select and switch statements may appear similar on the surface, their purposes and functions are different. switch is used for conditional branching, while select is used for channel operations. Only channel operations are allowed within a select statement.

Usage Rules: While the syntax is straightforward, there are some important considerations when using select. Here are four key points:

  1. The select statement can only be used for channel operations to choose among multiple channels and listen for their readiness. It is not used for other types of conditional checks.
  2. The select statement can include multiple case clauses, each corresponding to a channel operation. When any of the channels becomes ready, the corresponding case clause is executed.

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

Responses (1)