In this post, we’ll delve into the versatile switch
statement in Golang, a powerful construct that allows you to execute different actions based on various situations. This statement not only handles specific cases but can also be used for expressing if/else logic without an explicit expression.
What’s Inside
Understanding the Switch Statement
Golang’s switch
statement is akin to those found in languages like PHP and Java. Let’s look at the syntax:
switch expression { case exp1: statement1 case exp2: statement2 case exp3: statement3 // ... default: statement4 }
Commas can be used to separate multiple expressions in the same case statement. You can also include a default
case, which will be executed if none of the other cases match.
Types of Switch Statements
Golang supports two types of switch statements:
- Expression Switch: This type is used to select one of many code blocks based on the value of the expression.
- Type Switch: Unlike expression switch, this type compares types instead of values. It matches the type in the switch expression.
Example Using Switch Expression
Let’s explore a simple example using a switch expression to determine if it’s the weekend:
package main import ( "fmt" "time" ) func main() { switch time.Now().Weekday() { case time.Saturday, time.Sunday: fmt.Println("It's the weekend") default: fmt.Println("It's a weekday") } }
Output:
It's a weekday
Example Using Switch Type
In a type-switch block, only interfaces can be used. Here’s an example:
package main import "fmt" func main() { var value interface{} switch q := value.(type) { case bool: fmt.Println("Value is of boolean type") case float64: fmt.Println("Value is of float64 type") case int: fmt.Println("Value is of int type") default: fmt.Printf("Value is of type: %T", q) } }
Output:
Value is of int type
By mastering the switch
statement and its types, you gain a powerful tool for handling various scenarios in your Golang programs.
You May Also Like: