Choose cases with switch
Choose cases with switch
An expression switch compares its expression with case expressions and executes the first matching case. Use it for several alternatives of the same value. The optional default handles no match. Cases do not automatically fall through into the next case.
package main
import "fmt"
func main() { command := "start" switch command { case "start": fmt.Println("starting") case "stop": fmt.Println("stopping") default: fmt.Println("unknown command") }}The switch expression is evaluated once. Case expressions are evaluated in source order until a match is found. The matching statements run, then control leaves the switch. No break is necessary for ordinary cases.
Use a numeric switch
package main
import "fmt"
func main() { status := 404 switch status { case 200: fmt.Println("OK") case 404: fmt.Println("not found") default: fmt.Println("other status") } fmt.Println("done")}Each case uses a colon, not braces around its body. The expression and case values must support equality comparison under Go rules. Duplicate constant cases are rejected by the installed compiler. Only one default is permitted, and it need not be last.
Try it locally
For mode := "edit", use switch to print read-only for view, editable for edit, and unknown for any other mode. Expected: editable.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Branching 03: Choose cases with switch
Check the lesson objective before moving on.
What happens after an ordinary matched case finishes?
What happens if no case matches and there is no default?