SoFunction
Updated on 2025-03-01

Summary of the usage of Go language Select chan

The select statement is a keyword in Go language used to handle multiple channel operations. It allows you to perform non-blocking selection operations on multiple channels. The select statement can be used in the following situations:

Listen to multiple channels: You can listen to multiple channels at the same time. Once any of them is ready (with data readable or writable), select will select the first ready channel to perform the relevant operation.

Timeout operation: You can use select in conjunction with timer channels to implement timeout operation to ensure that you do not wait for the channel operation to complete indefinitely.

Avoid blocking: When a channel operation may cause a program to block, select can help you avoid blocking to keep your program responsive.

Example 1: Listen to multiple channels

package main
import (
	"fmt"
	"time"
)
func main() {
	ch1 := make(chan string)
	ch2 := make(chan string)
	go func() {
		(2 * )
		ch1 <- "Hello from ch1"
	}()
	go func() {
		(1 * )
		ch2 <- "Hello from ch2"
	}()
	select {
	case msg1 := <-ch1:
		(msg1)
	case msg2 := <-ch2:
		(msg2)
	}
}

In this example, we create two coroutines, each sending a message to a different channel. Then, use the select statement in the main coroutine to listen for both channels, and once one of them is ready, it prints the corresponding message.

Example 2: Timeout operation

package main
import (
	"fmt"
	"time"
)
func main() {
	ch := make(chan string)
	go func() {
		(2 * )
		ch <- "Hello from ch"
	}()
	select {
	case msg := <-ch:
		(msg)
	case <-(1 * ):
		("Timeout")
	}
}

In this example, we create a coroutine that sends messages to the channel after 2 seconds. Then, the channel operation is monitored using the select statement in the main coroutine, but a 1-second timeout timer is created using it. If the channel operation does not complete within 1 second, the timeout branch will be executed and "Timeout" is printed.

Example 3: Avoid blocking

package main
import (
	"fmt"
	"time"
)
func main() {
	ch := make(chan string)
	go func() {
		(2 * )
		ch <- "Hello from ch"
	}()
	select {
	case msg := <-ch:
		(msg)
	default:
		("No message received")
	}
}

In this example, we also created a coroutine, but used the default branch of the select statement. If the channel operation cannot be completed immediately, the default branch will execute, printing "No message received" without blocking the program.

This is the end of this article about the use of Select chan in Go language. For more related Go Select chan content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!