引入

程序不可能永远一条路走到黑,很多时候需要根据不同情况走不同的分支。条件判断就是让程序”做选择”的语法。Go 的条件判断有 ifswitch 两种,比很多语言简洁,但细节上有自己的风格。

正文

定义

定义

条件判断是根据表达式的真假来决定执行哪段代码。Go 提供 if-elseswitch 两种方式,switch 还支持按类型判断(type switch)。

语法

// if 基本写法
if condition {
    // 条件为 true 时执行
}
 
// if-else
if condition {
    // true
} else {
    // false
}
 
// switch 基本写法
switch value {
case 1:
    // value == 1
case 2:
    // value == 2
default:
    // 都不匹配
}

例子

if 基础

age := 20
 
if age >= 18 {
    fmt.Println("成年")
}

Go 的 if 条件不需要加括号,这是和 C/Java 最大的区别。

if 带初始化语句

if score := getScore(); score >= 60 {
    fmt.Println("及格")
} else {
    fmt.Println("不及格")
}
// score 在 if-else 外面不可用

if 前面可以加一个初始化语句,用 ; 隔开。初始化的变量作用域只在 if-else 块内,这个写法在错误处理里特别常见:

if err := doSomething(); err != nil {
    fmt.Println("出错了:", err)
}

if-else if-else

score := 85
 
if score >= 90 {
    fmt.Println("A")
} else if score >= 80 {
    fmt.Println("B")
} else if score >= 70 {
    fmt.Println("C")
} else {
    fmt.Println("D")
}

Go 没有 elif,直接写 else if

switch 基础

day := "Monday"
 
switch day {
case "Monday":
    fmt.Println("周一")
case "Friday":
    fmt.Println("周五")
default:
    fmt.Println("其他")
}

Go 的 switch 自动 break,匹配到一个 case 就结束,不需要手动写 break。这和 C/Java 不同。

switch 多个值

switch day {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
    fmt.Println("工作日")
case "Saturday", "Sunday":
    fmt.Println("周末")
}

一个 case 可以列多个值,用逗号隔开。

switch 无条件表达式

score := 85
 
switch {
case score >= 90:
    fmt.Println("A")
case score >= 80:
    fmt.Println("B")
default:
    fmt.Println("C")
}

switch 后面不写表达式,相当于 switch true,每个 case 写完整条件。这种写法可以替代长串的 if-else if

fallthrough

n := 1
 
switch n {
case 1:
    fmt.Println("一")
    fallthrough  // 继续执行下一个 case
case 2:
    fmt.Println("二")
case 3:
    fmt.Println("三")
}
// 输出:一 二

fallthrough 让 switch 不自动 break,强制进入下一个 case。很少用,知道有这个语法就行。

type switch

func checkType(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Println("整数:", v)
    case string:
        fmt.Println("字符串:", v)
    case bool:
        fmt.Println("布尔值:", v)
    default:
        fmt.Println("未知类型")
    }
}
 
checkType(42)       // 整数: 42
checkType("hello")  // 字符串: hello
checkType(true)     // 布尔值: true

type switch.(type) 来判断接口值的实际类型,在处理未知类型的数据时很有用。

常见写法

写法说明
if cond { }基本条件
if init; cond { }带初始化的条件
if cond { } else if cond { } else { }多分支
switch val { case x: }值匹配
switch { case cond: }条件匹配,替代 if-else
switch v := i.(type) { }类型匹配

特点

  • if 条件不需要括号,但大括号 { 必须有
  • if 支持初始化语句,变量作用域限制在块内
  • switch 自动 break,不用手写
  • switch 可以没有表达式,当 if-else 链用
  • fallthrough 可以穿透到下一个 case,但实际很少用
  • type switch 是 Go 特有的,用来判断接口类型
  • Go 没有三元运算符 ? :,条件赋值老老实实用 if-else

理解

Go 的条件判断追求的是少即是多。没有三元运算符,没有复杂的 switch 穿透规则(默认自动 break),if 还支持局部变量初始化。这些设计让条件代码读起来更直白,不容易出逻辑漏洞。switchif-else 链更清晰,type switch 则是处理接口类型的利器。

引出

条件判断让程序能”选路走”,但有时候一段代码要重复执行很多次。接下来看 Go 循环,Go 只有一种循环语句,但够用。