The switch statement in Go is a powerful control mechanism that allows you to execute different blocks of code depending on the value of an expression. It serves as an alternative to the series of if statements with multiple conditions, providing a cleaner and more readable structure.
Basic Usage
Let's start with a basic example of the switch statement. Here, we will examine how it functions when checking a single variable against different case conditions.
package main
import (
"fmt"
)
func main() {
day := "Monday"
switch day {
case "Monday":
fmt.Println("Start of the work week.")
case "Friday":
fmt.Println("End of the work week.")
default:
fmt.Println("Midweek.")
}
}
This code will print "Start of the work week." because the variable day matches the "Monday" case.
Intermediate Example
We can also use multiple expressions in a single case and fallthrough to execute the next case block. Here’s how:
package main
import (
"fmt"
)
func main() {
number := 3
switch number {
case 1, 3, 5, 7:
fmt.Println("Odd number")
case 2, 4, 6, 8:
fmt.Println("Even number")
default:
fmt.Println("Number not in range 1-8")
}
}
In this example, since number has a value of 3, it prints "Odd number".
Advanced Usage
Besides switching based on constants, Go allows us to use expressions in switch:
package main
import (
"fmt"
"time"
)
func main() {
switch t := time.Now(); { // note: switch with no expression
case t.Hour() < 12:
fmt.Println("Good Morning!")
case t.Hour() < 18:
fmt.Println("Good Afternoon!")
default:
fmt.Println("Good Evening!")
}
}
Here, we switch based on the result of a boolean expression. The specific case gets executed based on the current hour. If the hour is before 12, it will print "Good Morning!", and so on.
Use switch without an Expression
It is also possible in Go to use a switch statement without an expression, which allows you to evaluate all the cases manually:
package main
import (
"fmt"
)
func main() {
num := 10
switch {
case num < 0:
fmt.Println("Negative Number")
case num == 0:
fmt.Println("Zero")
case num > 0:
fmt.Println("Positive Number")
}
}
This example evaluates the value of num within several conditions and prints "Positive Number" because num is greater than 0.
The flexibility and simplicity of the switch statement in Go make it preferable for many similar conditions over using multiple if-else statements.