The switch
statement in Go is a control structure used for selecting one block of code to execute from multiple options. Unlike some other programming languages such as C, C++, Java, JavaScript, and PHP, Go’s switch
statement does not require a break
statement to exit a case, as it automatically terminates after executing the matched case.
Single-Case switch
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. - The value of the
expression
is compared with the value in eachcase
. - If a match is found, the associated code block executes.
- The
default
block (optional) will execute if no case matches.
Example 1: Weekday Calculation
package main import ("fmt") func main() { day := 3 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") } }
Output (if day = 3
):
Wednesday
Example 2: Motorcycle Brand Selector
package main import ("fmt") func main() { model := "Ducati" switch model { case "Yamaha": fmt.Println("You selected Yamaha. Known for performance and reliability.") case "Honda": fmt.Println("You selected Honda. A favorite for its versatility.") case "Suzuki": fmt.Println("You selected Suzuki. Renowned for stylish designs.") case "Ducati": fmt.Println("You selected Ducati. Famous for its speed and luxury.") default: fmt.Println("Unknown brand. Please choose a valid motorcycle.") } }
Output (if model = "Ducati"
):
You selected Ducati. Famous for its speed and luxury.
The default Keyword
The default
keyword provides a fallback option when no case matches. For example:
package main import ("fmt") func main() { day := 10 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") } }
Output (if day = 10
):
Invalid day
Example 3: Type Check Error
Ensure all case values are of the same type as the switch
expression. Mixing types will result in a compilation error. Here’s an illustration:
package main import ("fmt") func main() { engineType := 4 switch engineType { case 1: fmt.Println("Engine type is single-cylinder.") case "v-twin": fmt.Println("Engine type is a v-twin.") // This will cause an error! } }
Result:
./prog.go:11:2: cannot use "v-twin" (type untyped string) as type int