Go 语言提供了基本的条件控制语句,帮助开发者根据不同的条件执行不同的代码。Go 中的常见条件语句有 if
语句、else
语句、else if
语句以及 switch
语句。这些语句允许程序根据条件判断来决定程序的执行路径。
目录
1. if 语句
if
语句是最基本的条件语句,用于判断给定的条件是否成立。如果条件为 true
,则执行对应的代码块,否则跳过。
1.1 基本语法
1 2 3 | if 条件 { // 条件为 true 时执行的代码 } |
示例:
1 2 3 4 5 6 7 8 9 10 11 | package main import "fmt" func main() { a := 10 if a > 5 { fmt.Println("a is greater than 5") } } |
输出:
1 | a is greater than 5 |
2. if-else 语句
if-else
语句提供了在条件不成立时执行的另一个代码块。即如果条件为 false
,则执行 else
部分的代码。
2.1 基本语法
1 2 3 4 5 | if 条件 { // 条件为 true 时执行的代码 } else { // 条件为 false 时执行的代码 } |
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 | package main import "fmt" func main() { a := 3 if a > 5 { fmt.Println("a is greater than 5") } else { fmt.Println("a is less than or equal to 5") } } |
输出:
1 | a is less than or equal to 5 |
3. if-else if-else 语句
if-else if-else
语句允许你进行多个条件的判断。它可以依次判断多个条件,直到找到满足的条件。如果所有条件都不满足,则执行 else
部分。
3.1 基本语法
1 2 3 4 5 6 7 | if 条件1 { // 条件1为 true 时执行的代码 } else if 条件2 { // 条件2为 true 时执行的代码 } else { // 条件1和条件2都为 false 时执行的代码 } |
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package main import "fmt" func main() { a := 7 if a > 10 { fmt.Println("a is greater than 10") } else if a > 5 { fmt.Println("a is greater than 5 but less than or equal to 10") } else { fmt.Println("a is less than or equal to 5") } } |
输出:
1 | a is greater than 5 but less than or equal to 10 |
4. switch 语句
switch
语句是多条件判断的一种简洁方式,可以代替多个 if-else if
语句。它根据变量的值来执行匹配的代码块。
4.1 基本语法
1 2 3 4 5 6 7 8 | switch 变量 { case 条件1: // 条件1匹配时执行的代码 case 条件2: // 条件2匹配时执行的代码 default: // 所有条件都不匹配时执行的代码 } |
4.2 注意事项
switch
语句会自动进行值的匹配。switch
语句的case
可以是常量表达式,但可以不完全列举所有条件。default
是可选的,用于处理所有未匹配的情况。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package main import "fmt" func main() { day := 3 switch day { case 1: fmt.Println("Monday") case 2: fmt.Println("Tuesday") case 3: fmt.Println("Wednesday") case 4: fmt.Println("Thursday") case 5: fmt.Println("Friday") case 6: fmt.Println("Saturday") case 7: fmt.Println("Sunday") default: fmt.Println("Invalid day") } } |
输出:
1 | Wednesday |
4.3 switch 语句的表达式
Go 的 switch
语句可以使用任何类型的表达式,而不仅限于常量。也可以省略 switch
后面的表达式,默认使用 true
来进行逐一比较。
示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package main import "fmt" func main() { a := 3 switch { case a > 5: fmt.Println("a is greater than 5") case a == 3: fmt.Println("a is equal to 3") default: fmt.Println("a is some other value") } } |
输出:
1 | a is equal to 3 |
5. 参考资料
通过掌握 Go 语言中的条件语句,开发者可以实现更为复杂的逻辑控制和多种场景下的决策判断。if
、else
、switch
语句的使用,可以让程序在运行时根据不同的条件执行不同的操作。
发表回复