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

About the understanding of select in golang

藏色散人
Release: 2020-08-26 11:46:45
forward
2894 people have browsed it

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!"
Copy after login

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")}
Copy after login

You will get the following results

Case 1 is selected
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template