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.

GoCli Tooling

Code

gosnippet
32 lines
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

FAQ

How do you run Switch Without Expression Falls Through?
The runtime alone is enough: execute the file as a complete program.