SoFunction
Updated on 2025-03-05

Introduction to the usage of select statements in Go language

The syntax of the select statement in the Go programming language is as follows:

Copy the codeThe code is as follows:

select {
    case communication clause  :
       statement(s);     
    case communication clause  :
       statement(s);
    /* you can have any number of case statements */
    default : /* Optional */
       statement(s);
}

The following rules apply to the select statement:

There can be any number of cases to choose. The values ​​followed by the heel are compared in each case, and a colon.

The type of case must be a communication channel operation.

This will be executed when the channel runs the statement below. break is not required in case statement.

The select statement can have an optional default case, which must appear before the end of the select. By default, it is true if not when executing a task. Break is not required by default.

For example:

Copy the codeThe code is as follows:

package main

import "fmt"

func main() {
   var c1, c2, c3 chan int
   var i1, i2 int
   select {
      case i1 = <-c1:
         ("received ", i1, " from c1\n")
      case c2 <- i2:
         ("sent ", i2, " to c2\n")
      case i3, ok := (<-c3):  // same as: i3, ok := <-c3
         if ok {
            ("received ", i3, " from c3\n")
         } else {
            ("c3 is closed\n")
         }
      default:
         ("no communication\n")
   }   
}

 
Let's compile and run the above program, which will produce the following results:
no communication