SoFunction
Updated on 2025-03-03

Example of usage of Go language select statement

usage

A dedicated statement—select statement for sending and accepting information in multiple channels. The select statement blocks until one of the send/receive operations is ready. The select statement is somewhat similar to the switch statement, but the select statement will select one of the branches when it is executed, and the method of selecting branches is completely different.

ch1 = make(chan string)
ch2 = make(chan string)
ch1 <- "server1"
ch2 <- "server1"
select {
    case i := <- ch1:
      ("Readed data %d from ch1", i)
    case j := <- ch2:
      ("Readed data %d from ch2", i)
    default:
      ("no action...", i)
}

In the above code, each case is only for the reception statement of a certain channel. This is different from switch and there is no break. The switch statement is a switch expression to the right, but the select is in curly braces to the right.

When starting to execute the select statement, all expressions that follow the right of the case keyword will be evaluated, and the order of evaluation is from top to bottom, from left to right.

Use scenarios

Implement the sending and receiving function

select is an indispensable part of controlling the channel. The main function of the channel is to send and receive information. Based on this, a producer and consumer function can be designed. Producer sends messages, consumers accept messages

func main(){
// Production data, write data to channel  n1 := make(chan int)
    go func() {
        i := 0
        for {
            (((1000)) * )
            n1 <- i
            i++
        }
    }()
    n2 := make(chan int)
    go func() {
        i := 0
        for {
            (((1000)) * )
            n2 <- i
            i++
        }
    }()
// When reading data from the channel, output    for {
        select {
        case n := <-n1:
            ("Readed data %d from ch1", n)
        case n := <-n2:
            ("Readed data %d from ch1", n)
        }
    }
}

Things to note

  • select can only be used for chan IO operations
  • The case of select is in parallel. The case will be executed when the data is read, but if it is not read and default is not set, it will cause blockage.
  • Try to set default to avoid the select statement blocking when no IO operation occurs until a case branch hits
  • If it is empty, it may cause deadlock, so during the execution of the select, a case branch must be hit.
select {}
  • There is another way to prevent blockage: set the timeout

The above is the detailed content of the usage example of Go select statement. For more information about Go select statements, please pay attention to my other related articles!