Introduction to the use of select statements in the Go language

  • 2020-05-30 20:21:09
  • OfStack

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

select {
    case communication clause  :
    case communication clause  :
    /* you can have any number of case statements */
    default : /* Optional */

The following rules apply to select statements:

You can select 1 case statement in any number of ranges. Each case is followed by a comparison of the value and a colon.

For case the type must be 1 communication channel operation.

This happens when the channel runs the following statement. break is not required in the case statement.

The select statement can have an optional default of case, which must appear before the end of select. By default, this is true if the task is not available at the time of execution. break is not required by default.

Such as:

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

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

no communication

Related articles: