乐闻世界logo
搜索文章和话题

How to Use the 'select' Statement in Golang?

2月7日 11:09

In Go, the select statement is used to handle sending and receiving operations on multiple channels. When you need to wait for multiple I/O operations concurrently, select allows your code to wait for multiple channel operations, and when one channel is ready, it executes the corresponding case statement.

Below is the basic usage of the select statement:

go
package main import ( "fmt" "time" ) func main() { c1 := make(chan string) c2 := make(chan string) go func() { time.Sleep(2 * time.Second) c1 <- "one" }() go func() { time.Sleep(1 * time.Second) c2 <- "two" }() for i := 0; i < 2; i++ { select { case msg1 := <-c1: fmt.Println("Received", msg1) case msg2 := <-c2: fmt.Println("Received", msg2) } } }

In this example, we create two channels c1 and c2, and send data to them in different goroutines. In the main function's for loop, we use the select statement to receive data. select will block until one channel is ready for receiving. Once this happens, the corresponding case statement is executed.

The select statement can also be used with the default clause to avoid blocking:

go
select { case msg1 := <-c1: fmt.Println("Received", msg1) case msg2 := <-c2: fmt.Println("Received", msg2) default: fmt.Println("No message received") }

In this version, if no channels are ready, select will execute the default clause instead of blocking.

The select statement is a powerful tool for handling concurrent operations and communication between goroutines, especially useful when dealing with multiple channels.

标签:Golang