Golang - If every case in switch case is evaluated, what is the order?

WBOY
Release: 2024-02-08 22:21:09
forward
486 people have browsed it

Golang - 如果 switch case 中的每个 case 都进行评估,那么顺序是什么?

php editor Baicao is here to answer a question about Golang: "If each case in the switch case is evaluated, what is the order?" In Golang, The execution order of switch statements is from top to bottom, that is, they are evaluated in the order of cases in the code. Once a case is matched successfully, the corresponding code block will be executed, and then the program will jump out of the switch statement. If there is no matching case, the default statement (if any) will be executed. If there is no default statement, the switch statement will end directly. This is the order and execution rules of switch cases in Golang.

Question content

Suppose we have a switch box

switch {
  case true:
   fmt.Println(1)
  case true:
   fmt.Println(2)
Copy after login

What will be output?

I heard that golang will choose pseudo-random expressions, but I tested it in go-playground and found that it will follow the order from top to bottom, so the output will be 1

Solution

Execute the first case matching the switch statement:

https://www.php.cn/link/77772713a7d7e02b10ca9bd90e4f6a31

When multiple branches are ready to continue, pseudo-random selection occurs in the select statement rather than in the switch.

The above is the detailed content of Golang - If every case in switch case is evaluated, what is the order?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!