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 variable. When the condition matches the value of a certain case
statement, the corresponding case
statement will be executed, and after the execution, it will exit the current switch
branch.
The variable value in the case
statement needs to be of the same type.
The program will match from top to bottom in the case
statement and execute the code of the branch that matches the condition. After the execution is complete, it will exit the current switch
branch.
The default
statement is similar to the else
statement. When other case
statements do not 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:
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.â")
}
}
After running the code, 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.