Understanding the switch Statement in Go
In Go, the switch statement is a powerful way to choose one out of many possible code blocks to execute based on the value of an expression.
It's similar to switch statements in other languages like C, C++, Java, JavaScript, and PHP — but with one major difference: Go does not require break statements. When a case matches, only that block runs, and the switch exits automatically.
Syntax: Single-Case switch
switch expression {
case value1:
// code block if expression == value1
case value2:
// code block if expression == value2
case value3:
// and so on...
default:
// code block if no case matches (optional)
}
How it Works
- The expression is evaluated only once.
- Its value is compared against the values in each case.
- When a match is found, the corresponding block is executed.
- The default block (if present) runs when no case matches — it’s optional.
Single‑Case switch Example in Go
Below is a cleaner rendition that converts a weekday number into its name.
Because Go’s switch exits after the first match, we don’t need any break statements.
package main
import "fmt"
func main() {
day := 4
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Invalid day number")
}
}
Output when day is 4:
Thursday
Using the default Case in a switch
The default branch tells Go what to do when none of the listed cases match. It’s optional, but it’s good practice when you need a fallback.
Example
package main
import "fmt"
func main() {
day := 8 // an out‑of‑range value
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
default:
fmt.Println("Not a weekday")
}
}
Output with day := 8:
Not a weekday
Consistent Case Types in a switch
In Go, every case value must be the same type as the switch expression.
If you mix types—say, comparing an int expression with a string case—the compiler will stop you.
Example Showing the Error
package main
import "fmt"
func main() {
a := 3 // a is an int
switch a { // switch expression is int
case 1: // OK: 1 is an int
fmt.Println("a is one")
case "b": // ERROR: "b" is a string, not an int
fmt.Println("a is b")
}
}
Compiler output:
./prog.go:11:2: cannot use "b" (type untyped string) as type int
The string "b" cannot be compared with the integer a.