Home  >  Article  >  Backend Development  >  Golang - If every case in switch case is evaluated, what is the order?

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

WBOY
WBOYforward
2024-02-08 22:21:09488browse

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)

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!

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