Single-Case Switch in Go #
A single-case switch is the basic form of a switch statement where each case represents one specific value.
Syntax #
switch expression {
case x:
// code block
case y:
// code block
case z:
// code block
default:
// code block
}
How it works: #
- The
expression
is evaluated once. - Its value is compared with the values of each
case
. - If a match is found, the associated block executes.
- The
default
keyword is optional and executes if no case matches.
Single-Case Switch Example #
The example below uses a weekday number to calculate the weekday name:
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")
}
}
Result:
Thursday
The default
Keyword
#
The default
keyword specifies code to run if there is no case match:
package main
import ("fmt")
func main() {
day := 8
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")
}
}
Result:
Not a weekday
Important Note #
All case values must have the same type as the switch expression. Otherwise, the compiler will raise an error:
package main
import ("fmt")
func main() {
a := 3
switch a {
case 1:
fmt.Println("a is one")
case "b": // ❌ Error: different type
fmt.Println("a is b")
}
}
Result:
./prog.go:11:2: cannot use "b" (type untyped string) as type int