How does switch differ from C, and what does this fallthrough example print?
Question 24MediumGo 1.22 to 1.25
switch x := 2; x {
case 1:
fmt.Println("one")
case 2:
fmt.Println("two")
fallthrough
case 3:
fmt.Println("three")
fallthrough
case 100:
fmt.Println("hundred")
default:
fmt.Println("default")
}
Output: two, three, hundred (each on its own line).
Go cases don't fall through by default. After a matching case finishes, the switch ends. fallthrough moves control to the first statement of the next case without checking that case's condition. That is why case 100 runs even though x is 2. Execution stops at hundred because that case has no fallthrough, so default never runs.
Rules and differences from C:
fallthroughmust be the last statement in a case. It can't be used in the final case or in a type switch.- Cases can list several values (
case 'a', 'e', 'i':), and those values don't have to be constants. - Duplicate constant cases are a compile error.
- A
switchwith no expression meansswitch true, which is a clean way to write if/else chains. Cases are checked from top to bottom and stop at the first match. defaultcan appear anywhere in the list. It is still used only when no other case matches.
More on Language Fundamentals & Types
- Q22How do labeled
breakandcontinuework? Why does a plainbreakinsideselectnot leave the loop? - Q23What restrictions does Go place on
goto? - Q25Which types are comparable in Go, and when does comparing values panic at run time?
- Q26How does struct and array equality work? What is surprising about NaN as a map key?
- Q27What does the
comparableconstraint mean in generics, and what changed in Go 1.20? - Q28Explain method sets. Why does
var s Speaker = Dog{}fail to compile?