Switch Without Expression Falls Through
Use a tagless switch as a flat condition chain, then steer fallthrough deliberately: it enters the next case body unconditionally unless break exits.
Code
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))
}
}Inside the snippet
The short version: the work belongs to the functions classify and main, doing all the work.
Iteration happens inside for _, code := range []int{503, 404, 200, 0, -1} — everything outside it runs once.
Putting it to use
The primary signature, spelled out, is func classify(code int) []string
The entry point wires classify together — run it once and the whole demo flows.
Core lines
for _, code := range []int{503, 404, 200, 0, -1} {
fmt.Println(code, "->", classify(code))
}
actions = append(actions, "alert", "retry")
actions = append(actions, "notify")
Interactive Tools for This Topic
Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- How do you run Switch Without Expression Falls Through?
- The runtime alone is enough: execute the file as a complete program.
Report a problem with this exampleOpens a pre-filled issue on GitHub.