流程控制
# 流程控制
Go 使用 if、switch、for 控制流程。条件不需要括号,但代码块必须使用大括号。
func level(latency int) string {
switch {
case latency < 0:
return "invalid"
case latency < 100:
return "fast"
case latency < 500:
return "normal"
default:
return "slow"
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
Go 只有 for 一种循环形式,可写成计数循环、条件循环或无限循环。range 可遍历数组、切片、Map、字符串和 Channel。switch 默认不会向下贯穿,不需要手写 break。
使用 continue 跳过当前循环,使用 break 结束循环。嵌套结构较深时应优先拆分函数,而不是依赖复杂标签跳转。