Go•Switch Statement
Go Switch Statement: No Break Required and Multiple Cases
In Go, cases do not fall through by default (no break needed). Multiple values can be comma-separated.
Syntax
switch val {
case "a", "b":
// code
default:
// fallback
}
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| fallthrough | Keyword | Explicitly forces execution into the next case body. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Go locally:
package main
import "fmt"
func main() {
protocol := "POST"
fmt.Printf("Evaluating protocol: %s\n", protocol)
switch protocol {
case "GET":
fmt.Println(" Action: Retrieve existing data")
case "POST", "PUT":
fmt.Println(" Action: Mutate or save database record")
case "DELETE":
fmt.Println(" Action: Destroy record")
default:
fmt.Printf(" Action: Unsupported verb %s\n", protocol)
}
}Expected Output:
Evaluating protocol: POST Action: Mutate or save database record
How It Works: Step-by-Step
- Lines 9-19: switch matches protocol without requiring explicit break statements.
- Lines 12-13: Combines POST and PUT with comma separation.
Key Concepts
- Go cases break automatically after executing.
- To fall through into the next case, use the explicit fallthrough keyword.
- Switch can be tagless (switch without expression), acting like clean if-else chains.
Common Mistake: Writing unnecessary break statements at the end of each case
Go does not require break in switch cases. While harmless, it is unidiomatic.
❌ Incorrect
case "A": doWork(); break; // Redundant break
✅ Correct
case "A": doWork();
Related Go Tutorials & Compiler
Go If Statements with Inline Variable Initialization and Scope Limiting
Master Go if statements with compact inline variable initialization (if init; condition), keeping variables tightly scoped to branch blocks.
Go Unified For Loop: Traditional, While-Style, and Range Iteration
Master Go unified for loop (the only looping keyword in Go), implementing 3-component counters, while-style conditions, infinite loops, and range iteration.
Go Multiple Return Values and Error Handling Signatures
Master Go signature multiple return values, named returns, and the idiomatic (result, error) convention without exceptions.
Go Online Compiler
Open in Compilra IDE
Run and test Go on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.