Go language - switch case | judging multiple values in switch, interface conversion: interface {} is float64, not int

Go language - switch case

background

When there are few nested ifs (within three), writing programs with ifs is more concise. However, when there are many selected branches, there will be many levels of nested if statements, resulting in a verbose program and reduced readability. Therefore, the switch statement is used to handle multi-branch selection.

The Golang language also has the three Musketeers of if, switch, and for that other languages ​​have in terms of process control. Among them, the usage of if and for is basically the same. The usage of switch is quite different.

  • The biggest difference between switch and other languages ​​is that there is no break statement, and each case has a break statement by default.
  • A special usage of switch in Golang - fallthrough. The role of the fallthrough statement is to force the execution of the unexecuted case code after the case

switch case

A switch is a conditional statement that matches the evaluation result of an expression against a list of possible values ​​and executes the appropriate code based on the match. Think of the switch statement as an alternative to writing multiple if-else clauses. Compared with other languages ​​such as C and Java, the switch structure in Go language is more flexible to use.

switch var1 {
    
       //前花括号 { 必须和 switch 关键字在同一行。
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}

Each case
branch of the case is unique and is tested one by one from top to bottom until it matches. (The Go language uses a fast lookup algorithm to test the match of the switch condition with the case branch until the algorithm matches a case or enters the default condition). Once a branch is successfully matched, the entire switch code block will be exited after executing the corresponding code, that is to say, there is no need to use the break statement to indicate the end. Therefore, the program does not automatically execute the code of the next branch.

After a case statement, curly braces are not required to enclose multi-line statements. When the code block is only one line, it can be placed directly after the case statement. You can use the return statement to prematurely end the execution of a block of code.

default
The optional default branch can appear in any order, but it is best to put it last. It acts like the else in an if-else statement, indicating that the associated statement is executed if any of the given conditions are not met.

fallthrough
If you want to continue to execute the code of subsequent branches after executing the code of each branch, you can use the fallthrough keyword to achieve the purpose.

Special usage of switch in Golang - fallthrough

switch is executed from the first case whose judgment expression is true. If the case has fallthrough, the program will continue to execute the next case, and it will not judge whether the expression of the next case is true.

package main

import "fmt"

func main() {
    
    
    num := 2
    switch num{
    
    
    case 1:
        fmt.Println("num的数值是1")
    case 2:
        fmt.Println("num的数值是2")
	fallthrough
    case 3:
        fmt.Println("num的数值是3")
    case 4,5,6:
        fmt.Println("num的数值可能是4,5,6")
    default:
	fmt.Println("执行default语句")
    }
    fmt.Println("程序结束了")
}

Judging multiple values ​​in go language switch

The switch statement in the go language can easily determine the situation of multiple values.
The go language switch statement can match multiple conditions at the same time, separated by commas, and one of them can be successfully matched

package main
import "fmt"
 
func judge(v int) {
    
    
	switch v {
    
    
	case 1, 3:
		{
    
    
			fmt.Println("v的值为", v)
		}
	default:
		{
    
    
			fmt.Println("未匹配到,v的值为", v)
		}
	}
}
 
func main() {
    
    
	a := 1
	judge(a)
 
	a = 2
	judge(a)
 
	a = 3
	judge(a)
}

Code execution result:
The value of num is 2
The value of num is 3 The
program ends

Through the code, we can know that fallthrough only acts on the current case, and only executes one more case down, instead of executing the entire switch statement.

Type Switch, to determine the type of variable actually stored in an interface variable

The switch statement can also be used in type-switch to determine what type of variable is actually stored in an interface variable.

The syntax of Type Switch is as follows:

switch x.(type){
    
    
    case type:
       statement(s);      
    case type:
       statement(s); 
    /* 你可以定义任意个数的case */
    default: /* 可选 */
       statement(s);
}

The result of executing the above code is:

Type of x :

What data types are supported by golang switch

Java supports
1. The data type after the switch expression only supports byte, short, int integer type, character type char, enumeration type and java.lang.String type.
2. Note: The wrapper class of byte, short and int is supported, because it will be automatically unboxed

Switch in Go
supports any type

test float64

package main

import "fmt"

func main() {
    
    
	var num float64
	num = 1.0
	switch num {
    
    
	case 1:
		fmt.Println("num的数值是1")
	case 2:
		fmt.Println("num的数值是2")
		fallthrough
	case 3:
		fmt.Println("num的数值是3")
	case 4, 5, 6:
		fmt.Println("num的数值可能是4,5,6")
	default:
		fmt.Println("执行default语句")
	}
	fmt.Println("程序结束了")
}

I have a problem at work, interface conversion: interface {} is float64, not int

Description of the problem:
I encountered a job, use map[string]interface{} json to map to map, get a variable, and the log prints out 1, but the switch case is 1 and the life and death can't match.

First debug, I found that my data is of float64 type, but the switch to write demo float64 go should also support it. In order to be more secure, the general case uses integers, so I consider converting to int first. The result is an error: interface conversion: interface {} is float64, not int

Problem analysis:
The interface {} interface type cannot be directly cast to the int integer type. interface {} The interface type is float64. If you want to get an int integer value, you need to convert it to float first.

Note: Don't just look at the print. You see that the print result is 1 but it doesn't match case 1:. Before using interface{}, you have to manually turn xxx.(float64)it. The print can be typed out because go does this work internally when printing.

Other references
Solution: interface conversion: interface {} is float64, not int
Reference URL: https://developer.aliyun.com/article/850297

Notes on switch statement in go language

By default, switch in go is equivalent to having a break at the end of each case. After a successful match, other cases will not be automatically executed downward, but the entire switch will be jumped out.

Guess you like

Origin blog.csdn.net/inthat/article/details/127308743