Go switch Statement:

The switch statement in Go is a clean and efficient way to perform multiple conditional checks. It evaluates an expression and executes the first matching case.

Basic switch Example

A basic switch statement compares a value against several conditions:

go
day := "Tuesday"
switch day {
case "Monday":
  fmt.Println("Start of the work week")
case "Tuesday":
  fmt.Println("Second day of work")
default:
  fmt.Println("Some other day")

Multiple Case Values

You can combine multiple values in a single case:

go
day := "Saturday"
switch day {
case "Saturday", "Sunday":
  fmt.Println("Weekend!")
default:
  fmt.Println("Weekday")

Switch Without Expression

Switch can be used without a condition; it acts like a cleaner if-else chain:

go
num := 8
switch {
case num < 0:
  fmt.Println("Negative")
case num == 0:
  fmt.Println("Zero")
case num > 0:
  fmt.Println("Positive")

Fallthrough Keyword

Use fallthrough to force the execution of the next case:

go
num := 2
switch num {
case 1:
  fmt.Println("One")
case 2:
  fmt.Println("Two")
  fallthrough
case 3:
  fmt.Println("Three")

Switch with Type (Type Switch)

Go supports type switches to check the dynamic type of interface values:

go
var x interface{} = 10.5
switch v := x.(type) {
case int:
  fmt.Println("int:", v)
case float64:
  fmt.Println("float64:", v)
default:
  fmt.Println("Unknown type")