Basic Syntax
The syntax of the switch
branch statement is similar to that of the if
branch statement, as they both have conditional judgments. The basic syntax is as follows:
switch condition {
case val1:
// code block
case val2:
// code block
...
default:
// code block
}
The condition can be any type of expression. When the condition matches the value of a certain case
statement, the corresponding case
statement will be executed, and the program will then exit the current switch
branch.
The values in the case
statements must be of the same type as the condition expression.
The program will evaluate the case
statements from top to bottom and execute the first matching case
statement. After the execution is complete, it will exit the current switch
branch.
The default
statement is similar to the else
statement. When no other case
statements match the condition, the default
statement will be executed.
Let's take a look at an example of a weather forecast. Create a new file named switch.go
and write the following code:
cd ~/project
touch switch.go
package main
import (
"fmt"
)
func main() {
// Today's weather
weather := "rainy"
switch weather {
case "snow":
fmt.Println("Remember to wear a scarf today.ð§Ģ")
case "rainy":
fmt.Println("Remember to bring an umbrella today.ð")
default:
fmt.Println("Today is sunny.â")
}
}
Run the code:
go run switch.go
The output is as follows:
Remember to bring an umbrella today.ð
This weather forecast will output different results based on different weather conditions. First, we set today's weather as "rainy". In the switch-case
branch below, we set three different conditions. When it snows, we remind you to wear a scarf, when it rains, we remind you to bring an umbrella, and otherwise, we consider it as a sunny day.