An instance of Select statement usage in the Go language

  • 2020-05-26 09:17:21
  • OfStack

This article illustrates the use of Select statements in the Go language. Share with you for your reference. The specific analysis is as follows:

The select statement causes one goroutine to wait on multiple communication operations.
select blocks until one of the conditional branches can continue, and then that conditional branch is executed. When more than one is ready, one is chosen at random.

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:
   fmt.Println("quit")
                        return
                }
        }
}
func main() {
        c := make(chan int)
 quit := make(chan int)
 go func() {
  for i := 0; i < 10; i++ {
   fmt.Println(<-c)
  }
  quit <- 0
 }()
 fibonacci(c, quit)
}

The default option

The default branch is executed when no other conditional branch in select is ready.

For non-blocking send or receive, use the default branch:

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

package main
import (
 "fmt"
 "time"
)
func main() {
        tick := time.Tick(1e8)
        boom := time.After(5e8)
        for {
                select {
                case <-tick:
                        fmt.Println("tick.")
                case <-boom:
                        fmt.Println("BOOM!")
                        return
                default:
                        fmt.Println("    .")
                        time.Sleep(5e7)
                }
        }
}

I hope this article has helped you with your programming of Go.


Related articles: