GO Tutorial



SWITCH STATEMENT


Switch Statement in Go

The switch statement in Go provides an elegant way to execute different blocks of code based on the value of an expression. It’s cleaner and often more readable than multiple if-else statements.

Basic Switch Syntax

switch variable {
case value1:
    // code for value1
case value2:
    // code for value2
default:
    // code if no case matches
}
  

Example: Day of the Week

day := 3

switch day {
case 1:
    fmt.Println("Monday")
case 2:
    fmt.Println("Tuesday")
case 3:
    fmt.Println("Wednesday")
default:
    fmt.Println("Other day")
}
  

Multiple Values in a Case

You can match multiple values in a single case separated by commas.

grade := "B"

switch grade {
case "A", "A+":
    fmt.Println("Excellent")
case "B", "B+":
    fmt.Println("Good")
default:
    fmt.Println("Needs Improvement")
}
  

Switch Without an Expression

Go supports switch statements without an expression, where each case acts like an if condition.

num := 15

switch {
case num < 10:
    fmt.Println("Less than 10")
case num < 20:
    fmt.Println("Between 10 and 20")
default:
    fmt.Println("20 or more")
}
  

Fallthrough Keyword

By default, Go’s switch cases do not fall through to the next case. You can use the fallthrough statement to force the execution to continue to the next case.

score := 85

switch {
case score >= 90:
    fmt.Println("Excellent")
case score >= 80:
    fmt.Println("Very Good")
    fallthrough
case score >= 70:
    fmt.Println("Good")
default:
    fmt.Println("Keep Trying")
}
  

Summary

  • switch simplifies multi-way branching.
  • Cases can match single or multiple values.
  • Switch without an expression acts like if-else chains.
  • Use fallthrough carefully to continue execution to the next case.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review