条件判断
446字约1分钟
2025-02-03
if条件判断
在 Go 中,条件语句的圆括号不是必需的,但是花括号是必需的。
Go 没有三目运算符, 即使是基本的条件判断,依然需要使用完整的 if 语句。
package main
import "fmt"
func main() {
if true {
fmt.Println("True")
} else {
fmt.Println("False")
}
if true {
fmt.Println("True")
}
num := 10
if num > 10 { // if num := 10; num > 10 {
fmt.Println("数字大于 10")
} else if num == 10 {
fmt.Println("数字等于 10")
} else {
fmt.Println("数字小于 10")
}
}
switch分支
switch 是多分支情况时快捷的条件语句,相对于写N多的if else来判断多个条件,显然用 switch更简洁高效。
package main
import "fmt"
func main() {
// 示例1: 基本的Switch
fmt.Println("示例1:")
day := 3
switch day {
case 1:
fmt.Println("星期一")
case 2:
fmt.Println("星期二")
case 3:
fmt.Println("星期三")
default:
fmt.Println("其他日期")
}
// 示例2: 针对多个值的情况
fmt.Println("\n示例2:")
num := 3
switch num {
case 1, 3, 5:
fmt.Println("奇数")
case 2, 4, 6:
fmt.Println("偶数")
}
// 示例3: 在case中使用表达式
fmt.Println("\n示例3:")
score := 85
switch {
case score > 90:
fmt.Println("A 等级")
case score > 80:
fmt.Println("B 等级")
case score > 70:
fmt.Println("C 等级")
default:
fmt.Println("D 等级")
}
// 示例4: 使用fallthrough关键字
/* Go里面switch默认相当于每个case最后带有break,
匹配成功后不会自动向下执行其他case,而是跳出整个switch,
但是可以使用fallthrough强制执行后面的case代码。
*/
fmt.Println("\n示例4:")
number := 10
switch {
case number == 10:
fmt.Println("等于10")
fallthrough
case number >= 10:
fmt.Println("10 或更多")
}
// 示例5: 对类型进行Switch
fmt.Println("\n示例5:")
var x interface{}
x = 10
switch x.(type) {
case int:
fmt.Println("x 是一个整数")
case float64:
fmt.Println("x 是一个浮点数")
case string:
fmt.Println("x 是一个字符串")
default:
fmt.Println("未知类型")
}
}