2.22. Go language select statement

发布时间 :2023-10-12 23:00:09 UTC      

select is a control structure in Go , similar to the one used for communication switch statement. Each case must be a communication operation, either sending or receiving.

select randomly execute a runnable case . If not, case runnable, it will block until there is case can be run. A default clause should always run.

2.22.1. Grammar #

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

select {
    case communication clause  :
       statement(s);
    case communication clause  :
       statement(s);
    /* You can define any number of cases */
    default : /* optional */
       statement(s);
}

The following description describes select syntax of the statement:

  • Each case must be a communication.

  • All channel expressions are evaluated.

  • All expressions sent will be evaluated

  • If any communication can be performed, it is executed and the others are ignored.

  • If there are more than one case can be run. Select will be randomly and fairly selected for execution. The rest will not be carried out. Otherwise:

    1. If there is default clause, the statement is executed.

    2. If there is no default clause, select will block until a communication can run; Go will not re evaluate channel or values.

2.22.2. Example #

select statement application demonstration:

Example #

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")
         }
      default:
         fmt.Printf("no communication\\n")
   }
}

The result of the above code execution is:

no communication

Principles, Technologies, and Methods of Geographic Information Systems  102

In recent years, Geographic Information Systems (GIS) have undergone rapid development in both theoretical and practical dimensions. GIS has been widely applied for modeling and decision-making support across various fields such as urban management, regional planning, and environmental remediation, establishing geographic information as a vital component of the information era. The introduction of the “Digital Earth” concept has further accelerated the advancement of GIS, which serves as its technical foundation. Concurrently, scholars have been dedicated to theoretical research in areas like spatial cognition, spatial data uncertainty, and the formalization of spatial relationships. This reflects the dual nature of GIS as both an applied technology and an academic discipline, with the two aspects forming a mutually reinforcing cycle of progress.