In this post, we will see here how we can use the switch statement in the Golang. This allows you to conduct various actions in Golang based on various situations. If/else logic can also be expressed with a switch without an expression.
Golang also has a switch() statement, similar to those seen in other programming languages like PHP and Java.
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. We may also declare a default case, which will be used if none of the other cases match.
Go language supports two types of switch statements:
- Expression Switch : This switch statement is used to select one of many blocks of code to be executed based on the expression’s value.
- Type Switch : A type switch compares types instead of values.It will be compared to the type in the switch expression.
Simple Example Using Switch Expression
The below example is using a switch expression.
package main
import "fmt"
import "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
Simple Example Using Switch Type
In the expression of the type-switch block, only interfaces can be used. Let’s see below example for switch type:
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
