Go 条件判断
Go - 条件判断
Section titled “Go - 条件判断”条件判断结构对于控制程序的执行流程至关重要。它们允许您指定程序需要评估的条件,并根据这些条件的真假来执行不同的代码块。
本质上,您是在告诉程序:“如果这个条件为真,就做这个;否则,也许做那个,或者做点别的事情。”
Go 提供了几种用于条件判断的语句:
| 语句 | 描述 |
|---|---|
if 语句 | 仅在指定的布尔条件为真时执行一个代码块。 |
if...else 语句 | 如果条件为真,则执行一个代码块;如果条件为假,则执行另一个代码块。 |
if...else if...else 语句 | 按顺序测试多个条件。执行与第一个为真条件对应的代码块,如果没有条件为真,则执行 else 块。 |
嵌套 if 语句 | 将一个 if 或 if...else 语句放在另一个内部,可以实现更复杂的条件检查。 |
switch 语句 | 将表达式与一组可能的常量值(case)进行比较。执行与匹配的 case 关联的代码块。Go 的 switch 比许多其他语言更灵活。 |
select 语句 | 专为并发设计。等待多个 channel 操作,然后执行第一个就绪的 channel 操作所关联的代码块。结构上类似于 switch,但用于通信。 |
基本的 if 语句仅在其条件表达式求值为 true 时执行代码。
语法:
if boolean_expression { // Code executes if boolean_expression is true}Go 的 if 语句(和 switch)还可以包含一个在条件判断之前执行的短初始化语句。在此处声明的变量作用域仅限于 if(以及任何 else if/else)代码块。
带初始化语句的语法:
if initialization_statement; boolean_expression { // Code executes if boolean_expression is true // Variables from initialization_statement are accessible here}示例:
package main
import ( "fmt" "math/rand" "time")
func main() { rand.Seed(time.Now().UnixNano()) // 带初始化语句的 If if num := rand.Intn(100); num >= 50 { fmt.Printf("Got %d, which is >= 50\n", num) // 'num' 在这里可访问 } else { fmt.Printf("Got %d, which is < 50\n", num) // 'num' 在这里也可访问 } // fmt.Println(num) // 错误:'num' 在 if/else 块外部不可访问}if...else 语句
Section titled “if...else 语句”如果条件为真,则执行一个代码块;如果为假,则执行另一个代码块。
语法:
if boolean_expression { // Executes if condition is true} else { // Executes if condition is false}if...else if...else 语句
Section titled “if...else if...else 语句”允许检查多个条件。
语法:
if boolean_expression_1 { // Executes if condition 1 is true} else if boolean_expression_2 { // Executes if condition 1 is false AND condition 2 is true} else { // Executes if all preceding conditions are false}switch 语句
Section titled “switch 语句”switch 语句提供了一种替代冗长 if...else if 链的多路分支结构。它将表达式与多个 case 值进行比较。
Go 中的关键特性:
- 无自动穿透(fallthrough):执行在匹配的
case块后停止(与 C/Java 不同)。如果需要穿透,请明确使用fallthrough关键字。 - case 可以是表达式,而不仅仅是常量。
- 没有表达式的
switch类似于switch true,对于更简洁的if/else if逻辑很有用。 - 可以包含像
if一样的初始化语句。
语法:
switch optional_initializer; optional_expression {case value1: // Code for value1case value2, value3: // Multiple values per case // Code for value2 or value3case expression_evaluating_to_value: // Code for matching expressiondefault: // Code if no case matches}select 语句
Section titled “select 语句”专门用于 channel 操作(发送或接收)。它会阻塞,直到其某个 case 操作可以进行,然后执行该 case。如果有多个 case 就绪,则随机选择一个。如果没有任何 channel 就绪,default case(如果存在)会立即执行。
语法:
select {case communication_clause1: // Statement(s) for case 1case communication_clause2: // Statement(s) for case 2...default: // Optional // Statement(s) if no other communication is ready}每种语句类型的详细示例可以在后续章节中找到,或者通过链接(如果可用)查看。