In this example, we will show you how to use the Switch/Case statement in Go with an example.
Go switch statement provides a multi-way execution. An expression or type specifier is compared to the cases inside the switch to determine which branch to execute. Unlike in other languages such as C, Java, or PHP, each case is terminated by an implicit break; therefore, we do not have to write it explicitly.
The default statement can be used for a branch that is executed, when no other cases fit. The default statement is optional.
Go - Switch/Case Statement Example 1
The below example demonstrates the usage of the Switch/Case statement in the Go language:
package main
import "fmt"
func main() {
switch day:=7; 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:
Sunday
Go - Switch/Case Statement Example 2
package main
import (
"fmt"
"time"
)
func main() {
// Basic Switch example
i := 2
fmt.Print("Write ", i, " as ")
switch i {
case 1:
fmt.Println("One")
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
}
// use commas to separate multiple expressions in the same case statement.
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
// switch without an expression is an alternate way to express if/else logic.
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("It's before noon")
default:
fmt.Println("It's after noon")
}
// A type switch compares types instead of values
whatAmI := func(i interface{}) {
switch t := i.(type) {
case bool:
fmt.Println("I'm a bool")
case int:
fmt.Println("I'm an int")
default:
fmt.Printf("Don't know type %T\n", t)
}
}
whatAmI(true)
whatAmI(1)
whatAmI("hey")
}
Output:
Write 2 as Two It's a weekday It's after noon I'm a bool I'm an int Don't know type string
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course