SoFunction
Updated on 2025-03-04

Summary of the usage of select keywords in golang

1. Official explanation

A select statement is used to select which case the send or receive operation can be executed immediately. It's similar to a switch statement, but its case involves channel-related I/O operations. That is, select is used to listen to IO operations related to channel. When the IO operation occurs, the corresponding action is triggered.

2. Key points

If one or more IO operations can be completed, the Go runtime system will randomly select one to execute. Otherwise, if there is a default branch, the default branch statement will be executed. If there is no default, the select statement will be blocked until at least one IO operation can be performed

All channel expressions will be evaluated, and all sent expressions will be evaluated. Evaluation order: from top to bottom, from left to right.

3. Usage

1. Use select to implement the timeout mechanism

timeout := make (chan bool, 1)
  go func() {
    (1e9) // sleep one second
    timeout <- true
  }()
  select {
  case <- timeout:
    ("timeout!")
  }

2. Use the select statement to check whether chan is full

ch2 := make (chan int, 1)
  ch2 <- 1
  select {
  case ch2 <- 2:
  default:
    ("channel is full !")
  }

3. for-select

package main

import (
  "fmt"
  "time"
)

func main() {
  var errChan = make(chan int)
  //Timed 2s  ticker := (2 * )
  defer ()
  go func(a chan int) {
    //Send a signal for 5s    ( * 5)
    errChan &lt;- 1
  }(errChan)
  LOOP:
    for {
      select {
        case &lt;-: {
          ("Task still running")
        }
        case res, ok := &lt;-errChan:
          if ok {
            ("chan number:", res)
            break LOOP
          }
      }
    }
  ("end!!!")
}
//Output result://Task still running
//Task still running
//chan number: 1
//end!!!

appendix:

select is a control structure in golang, similar to switch. Each case must be a communication operation, either send or accept.
select Randomly select a runnable case, and if no case can be run, it will block until a case can be run. A default sentence can always run.

select {
  case communication clause :
    statement(s)
  case communication clause :
    statement(s)
  default :
    statement(s)
}

The following describes the syntax of the select statement

  • Each case must be a communication
  • All channel expressions will be evaluated
  • All sent expressions will be evaluated
  • If any communication can be executed, it will be executed; others will be ignored
  • If multiple cases can be run, select will randomly and fairly select one execution. Others will not be executed.

otherwise

  • If there is a default clause, execute the statement
  • If there is no default clause, select will block until a communication can be executed; channel or value will not be evaluated repeatedly

Example

package main
import "fmt"
func fibonacci(c, quit chan int) {
  x, y := 0, 1
  for {
    select {
    case c <- x:
      x, y = y, x+y
    case <-quit:
      ("quit")
      return
    }
  }
}
func main() {
  c := make(chan int)
  quit := make(chan int)
  // start a goroutine to print current result
  // no buffer in c and quit channel, so this code
  // would block when this goroutine try to print
  go func() {
    for i := 0; i < 10; i++ {
      (<-c)
    }
    quit <- 0
  }()
  fibonacci(c, quit)
}

Summarize

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