Go 条件语句

Go 提供 if、switch、select 三种条件语句,按条件选择不同分支执行。以下片段省略外壳,均可放入 main 函数运行。

1. if 语句

if 的条件不加括号,但左花括号必须与 if 同一行:

age := 18
if age >= 18 {
    fmt.Println("成年了") // 输出: 成年了
}

2. if-else 多分支

条件为假时走 else;多个条件用 else if 串联:

score := 88
if score >= 90 {
    fmt.Println("优秀")
} else if score >= 80 {
    fmt.Println("良好") // 输出: 良好
} else {
    fmt.Println("继续加油")
}

3. 嵌套 if 与初始化语句

if 里可以再嵌套 if;if 前还可带一条初始化语句,其变量只在 if 块内有效:

age, ticket := 70, true
if ticket {
    if age >= 65 { // 嵌套判断
        fmt.Println("老年免票") // 输出: 老年免票
    }
}
if n := 100; n > 50 { // 初始化语句 n := 100
    fmt.Println("n 大于 50") // 输出: n 大于 50
}

4. switch 语句

多分支用 switch 更清晰,命中后自动跳出、无需 break:

day := 3
switch day {
case 1:
    fmt.Println("周一")
case 2, 3, 4, 5:
    fmt.Println("工作日") // 输出: 工作日
case 6, 7:
    fmt.Println("周末")
default:
    fmt.Println("非法输入")
}

5. type switch

v.(type) 判断接口变量的动态类型:

var v interface{} = 100
switch t := v.(type) {
case int:
    fmt.Println("整数:", t) // 输出: 整数: 100
case string:
    fmt.Println("字符串:", t)
default:
    fmt.Printf("未知类型: %T\n", t)
}

6. select 简述

select 用于 goroutine 并发中监听多个 channel,哪个就绪执行哪个:

select {
case msg := <-ch1:
    fmt.Println(msg)
case msg := <-ch2:
    fmt.Println(msg)
}

channel 与 select 的细节留待并发章节讲解。

小结

单分支用 if,多分支用 switch,判断动态类型用 type switch,并发等待用 select。

笔记加载中…