The switch statement in Go is a powerful control flow mechanism that allows you to execute different code blocks based on the value of an expression. It provides a cleaner and more efficient alternative to multiple if-else statements.
The basic syntax of a Go switch statement is as follows:
switch expression {
case value1:
// code block
case value2:
// code block
default:
// code block
}
The expression is evaluated once, and its value is compared against the values specified in each case. When a match is found, the corresponding code block is executed.
Go allows you to specify multiple cases for a single code block:
switch day {
case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday":
fmt.Println("It's a weekday")
case "Saturday", "Sunday":
fmt.Println("It's the weekend")
default:
fmt.Println("Invalid day")
}
Go supports switch statements without an expression, which can be used as an alternative to if-else chains:
switch {
case score >= 90:
fmt.Println("A")
case score >= 80:
fmt.Println("B")
case score >= 70:
fmt.Println("C")
default:
fmt.Println("F")
}
Unlike other languages, Go's switch cases break automatically. To execute the next case, use the fallthrough
keyword:
switch num {
case 1:
fmt.Println("One")
fallthrough
case 2:
fmt.Println("Two")
case 3:
fmt.Println("Three")
}
To further enhance your understanding of Go control flow, explore these related topics:
By mastering the switch statement and other control flow mechanisms, you'll be able to write more efficient and readable Go code.