Basics
Go Switch
Switch-Case Statements
Go switch statements handle cases with type switching support.
Introduction to Go Switch Statements
The switch statement in Go is a powerful control structure that allows you to execute one block of code among many options. Unlike other languages, Go's switch statement provides additional capabilities such as type switching and not needing break statements to terminate cases.
Basic Syntax of a Go Switch
Here's a simple example of a Go switch statement:
In this example, the switch statement evaluates the variable number
. If number
is 1, "One" is printed. If 2, "Two" is printed, and so on. If none of the cases match, the default case executes, printing "Other".
Type Switch in Go
Go switch statements also support type switching. This is useful when you need to assert the type of an interface variable. Here's how it works:
In this example, i
is an interface containing a string. The type switch checks the type of i
and executes the case that matches, printing "hello is a string".
Switch with Multiple Expressions
Go allows multiple expressions in a single case, separated by commas, making it more versatile:
In this example, if day
is either "Saturday" or "Sunday", it prints "Weekend". Otherwise, it defaults to "Weekday".
Conclusion
Go's switch statement is flexible and powerful, allowing for straightforward case handling and type assertions. Understanding how to effectively use switch statements can enhance your Go programming skills, making your code cleaner and more efficient.