This example describes the use of SELECT statements in the Go language. Share to everyone for your reference. The specific analysis is as follows:
The SELECT statement causes a goroutine to wait on multiple communication operations.
The select blocks until one of the conditional branches can continue, and then the conditional branch is executed. When more than one is ready, a random selection is done.
Copy Code code 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:
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)
}
Default selection
The default branch is executed when the other conditional branches in the Select are not ready.
For non-blocking send or receive, you can use the default branch:
Select {
case I: = <-c:
Use I
Default
Receiving from C-would block
}
Copy Code code as follows:
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 will help you with your go language program.