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.
switch variable {
case value1:
// code for value1
case value2:
// code for value2
default:
// code if no case matches
}
day := 3
switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
default:
fmt.Println("Other day")
}
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")
}
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")
}
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")
}
switch simplifies multi-way branching.fallthrough carefully to continue execution to the next case.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!