Home  >  Article  >  Backend Development  >  About the understanding of select in golang

About the understanding of select in golang

藏色散人
藏色散人forward
2020-08-26 11:46:452748browse

The following column will introduce to you the understanding of select in golang from the Golang Tutorial column. I hope it will be helpful to friends in need!

About the understanding of select in golang

The syntax of the Select statement is very similar to the Switch statement, but the Case in Select must be a communication operation (a Channel operation). The execution logic is: Which Channel operation behind the Case can be successfully executed, then the code block under the Case will be executed. If multiple Cases can be executed successfully at the same time, one of them is randomly selected. If none of the Cases can be successfully executed, the code block under default is executed. If there is no default, it will block and return a deadlock error.

Monitor IO operations. When IO operations occur, trigger corresponding actions.
This statement is correct. Monitoring (Channel's) IO operations and taking corresponding actions is indeed Select. Application scenarios, but do not mistakenly think that the Select statement is selecting which case the Channel operation is executed! This understanding is wrong! What Select will actually select is which case under which the Channel operation can be successfully executed, and then the code block under that case will be executed.

For example, when a piece of data is written to Channel c1

c1 := make(chan string, 1)c1 <- "Hello World!"

If we have the following Select judgment statement

select {
    case <-c1:
        fmt.Println("Case 1 is selected")
    case c1<-"Hello World!":
        fmt.Println("Case 2 is selected")
    default :
        fmt.Println("Default is selected")}

You will get the following results

Case 1 is selected

Because c1 has been written with a piece of data, we can successfully "read a piece of data from c1". That is, the first case can be executed successfully. Therefore, the code block under the first case is eventually executed.                                                                                                                                                        

The above is the detailed content of About the understanding of select in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete