Go language - control structure

Switch knowledge points:

After the switch/case is an expression (ie: constants, variables, a function with a return is fine);

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

Case can be followed by multiple expressions, separated by commas;

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

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

The default statement is not required;

Switch can also be used without an expression, similar to if --else branch;

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

Switch penetration: If fallthrough is added to the case statement, it will continue to execute the next case. By default, only one layer is penetrated, as follows:

package main
 
import "fmt"
 
func main() {
 
    switch {
    case false:
            fmt.Println("The integer was <= 4")
            fallthrough
    case true:
            fmt.Println("The integer was <= 5")
            fallthrough
    case false:
            fmt.Println("The integer was <= 6")
            fallthrough
    case true:
            fmt.Println("The integer was <= 7")
    case false:
            fmt.Println("The integer was <= 8")
            fallthrough
    default:
            fmt.Println("default case")
    }
}

type-switch: to determine the type of variable actually pointed to in the interface variable, for example:

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("未知型")
	}
}

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/128438496