Introduction to golang switch case statement

Note :

1. After switch/case is an expression (ie: constant, variable, and a function with a return);

2. The data type of the value of each expression after the case must be consistent with the data type of the switch expression;

3. There can be multiple expressions after case, separated by commas;

4. If the expression behind case is a constant value, it must not be repeated;

5. There is no need to bring a break after the case. After the program matches a case, the corresponding code block will be executed, and then the switch will be exited. If none of them match, the default will be executed;

6. The default statement is not necessary;

7. After switch, there can be no expression, similar to if --else branch to use;

8. You can also declare a variable directly after switch, ending with a semicolon, but it is not recommended.

9. Switch penetration: If fallthrough is added to the case statement, it will continue to execute the next case and only penetrate one layer by default.

10.type-switch: to determine the type of variable actually pointed to in the interface variable, such as:

package main

import (
	"fmt"
)

func main() {
	var x interface{}
	var y = 10
	x=y
	switch i := x.(type) {
	case nil:
		fmt.Printf("x的类型是:%T",i)
	case int:
		fmt.Printf("x是 int 类型")
	case float64:
		fmt.Printf("x是 float64 类型")
	case func(int) float64:
		fmt.Printf("x是func(int)类型")
	case bool,string:
		fmt.Printf("x是bool或者string类型")
	default:
		fmt.Printf("未知型")
	}
}

The execution result is as follows:Insert picture description here

Case : According to the month entered by the user, print the season that the month belongs to.

package main

import (
	"fmt"
)

func main() {
	//根据用户输入的月份,打印该月份所属的季节
	var month byte
	fmt.Print("请输入月份:")
	fmt.Scanln(&month)
	switch month {
		case 3, 4, 5:
			fmt.Println("春天")
		case 6, 7, 8:
			fmt.Println("夏天")
		case 9, 10, 11:
			fmt.Println("秋天")
		case 12, 1, 2:
			fmt.Println("冬天")
		default:
			fmt.Println("输入有误...")
	}
}

The execution result is shown in the figure below:
Insert picture description here

The choice of switch and if:

  1. If there are not many specific values ​​to be judged, and they conform to integers, floating-point numbers, characters, and character strings. It is recommended to use the switch statement, which is concise and efficient.
  2. Other situations: Use if for interval judgments and judgments that the result is bool type. If is used in a wider range.

 

 

Guess you like

Origin blog.csdn.net/whatday/article/details/113772678