判断语句

2026年9月6日

按条件走不同分支,Go 里就是 ifswitch。条件必须是布尔值,不能写 if 1


if 语句

常见例子:按年龄区间打印一句提示。这是「多选一」,可以写成三种样子。

中断式(卫语句)

先处理不满足的情况,用 return 提前离开,后面只留正常路径:

func hint(age int) {
	if age < 0 {
		fmt.Println("年龄无效")
		return
	}
	if age < 18 {
		fmt.Println("未成年")
		return
	}
	fmt.Println("成年")
}
go

这种写法叫卫语句:把门的条件挡在函数开头,主逻辑不再套很多层。

if 还可以带一句初始化,变量只在这个 if 里可见:

if n, err := fmt.Println("ok"); err == nil {
	fmt.Println("写了", n, "字节")
}
go

嵌套式

一层包一层,短的时候能看,深了就难读:

if age >= 0 {
	if age < 18 {
		fmt.Println("未成年")
	} else {
		fmt.Println("成年")
	}
} else {
	fmt.Println("年龄无效")
}
go

多条件式

else if 把区间摊平,一般比嵌套清楚:

if age < 0 {
	fmt.Println("年龄无效")
} else if age < 18 {
	fmt.Println("未成年")
} else if age < 35 {
	fmt.Println("青年")
} else {
	fmt.Println("中年及以上")
}
go

括号可以不写,花括号必须写。{ 要跟 if 同一行。


switch 语句

同一套年龄判断,用 switch 往往更直观。Go 的 switch 默认不会贯穿,匹配到一个 case 就结束,不必写 break

按条件:

switch {
case age < 0:
	fmt.Println("年龄无效")
case age < 18:
	fmt.Println("未成年")
case age < 35:
	fmt.Println("青年")
default:
	fmt.Println("中年及以上")
}
go

按值枚举:

switch day {
case 1, 2, 3, 4, 5:
	fmt.Println("工作日")
case 6, 7:
	fmt.Println("周末")
default:
	fmt.Println("不是 1–7")
}
go

case 里的值就是和 switch 后面那个表达式比。也可以带初始化:

switch n := age / 10; n {
case 1:
	fmt.Println("十几岁")
}
go

如果希望命中之后继续往下走(比如 12 岁既算未成年也想标青年),用 fallthrough

switch {
case age < 18:
	fmt.Println("未成年")
	fallthrough
case age < 35:
	fmt.Println("青年")
}
go

fallthrough无条件进入下一个 case 的函数体,不会再判断那个 case 的条件。能不用就不用。


参考文档