SoFunction
Updated on 2025-03-04

Example of the usage of Select statement in Go language

This article describes the usage of Select statements in Go language. Share it for your reference. The specific analysis is as follows:

The select statement causes a goroutine to wait on multiple communication operations.
select will block until one of the conditional branches can continue to execute, and that conditional branch will be executed. When multiple are ready, one will be selected randomly.

Copy the codeThe code is as follows:
package main
import "fmt"
func fibonacci(c, quit chan int) {
        x, y := 1, 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)
 go func() {
  for i := 0; i < 10; i++ {
   (<-c)
  }
  quit <- 0
 }()
 fibonacci(c, quit)
}

Default selection

When no other conditional branches in select are ready, the default branch will be executed.

For non-blocking transmission or reception, the default branch can be used:

select {
case i := <-c:
// use i
default:
// receiving from c would block
}

Copy the codeThe code is as follows:
package main
import (
 "fmt"
 "time"
)
func main() {
        tick := (1e8)
        boom := (5e8)
        for {
                select {
                case <-tick:
                        ("tick.")
                case <-boom:
                        ("BOOM!")
                        return
                default:
                        ("    .")
                        (5e7)
                }
        }
}

I hope this article will be helpful to everyone's Go language programming.