实现说明
真正干活的是函数 classify、main,其余都是接线。
在这里做循环的是 for _, code := range []int{503, 404, 200, 0, -1}。
使用要点
- 执行文件,
main会按顺序走完classify。
常见问题
「无表达式 switch 与 fallthrough」这个示例怎么运行?
文件自包含:直接运行,没有需要预先安装的依赖。
签名一览:func classify(code int) []string
核心语句
for _, code := range []int{503, 404, 200, 0, -1} {
fmt.Println(code, "->", classify(code))
}
actions = append(actions, "alert", "retry")
actions = append(actions, "notify")
代码示例
package main
import "fmt"
func classify(code int) []string {
var actions []string
// 无表达式的 switch:case 后跟布尔条件,等价 if/else 链但更平
switch {
case code >= 500:
actions = append(actions, "alert", "retry")
fallthrough // 无条件进入下一个 case 体,不再判断条件
case code >= 400:
actions = append(actions, "log")
if code < 500 {
break // break 提前退出,中断 fallthrough 链
}
fallthrough
case code > 0:
actions = append(actions, "notify")
case code == 0:
actions = append(actions, "noop")
default:
actions = append(actions, "reject")
}
return actions
}
func main() {
for _, code := range []int{503, 404, 200, 0, -1} {
fmt.Println(code, "->", classify(code))
}
}