Golang switch statement summary

The basic structure of a switch statement

switch 条件表达式 {
case 常量表达式1:
    语句 1
case 常量表达式2:
    语句 2
    .
    .
    .
case 常量表达式n:
    语句 n
default:
    语句 n+1
}

Implementation process

(1) Calculate the value of the conditional expression value

(2) If a value satisfying bar case statement, the statement is executed, executing the switch statement out

(3) If the value does not meet all of the case statement:

(3.1) if there is default, then execute the statement, executing the jump switch statement

(3.2) if there is no default, directly out of the switch statement

Precautions

(1) Go conditional expression can be any language supported data types

(3) does not need to break statement

(4) default branch is optional, but can only have a default branch

(5) If there are more than two constant expressions case branches to achieve the same value, the compiler will go wrong

Multi-case statement

Sometimes multiple conditions can be tested in a case statement values, any one of the conditions thereof are a case statement

func main() {
    var test string
    fmt.Print("请输入一个字符串:")
    fmt.Scan(&test)
    switch test {
    case "c":
        fmt.Println("c")
    case "java":
        fmt.Println("java")
    case "go", "golang":
        fmt.Println("hello golang")
    default:
        fmt.Println("python")
    }
}
// 请输入一个字符串:go
// hello golang

// 请输入一个字符串:golang
// hello golang

fallthrough statement

Typically, a switch statement qualified detected first case statement, the branch will execute code directly out of executing the switch statement. Use fallthroughstatement may be executed after the completion of the case statement, do not jump out, continue with the next case statement.

func main() {
    var test string
    fmt.Print("请输入一个字符串:")
    fmt.Scan(&test)
    switch test {
    case "go":
        fmt.Println("hello go")
    case "golang":
        fmt.Println("hello golang")
        fallthrough
    case "gopher":
        fmt.Println("hello gopher")
    case "java":
        fmt.Println("java")
    }
}
// 请输入一个字符串:go
// hello go

// 请输入一个字符串:golang
// hello golang
// hello gopher

Unconditional expression switch statement

If the switch keyword is not conditional expression, it must be conditional sentence in the case, that is similar to the if else ifstatement

func main() {
    var score int
    fmt.Print("请输入成绩:")
    fmt.Scan(&score)
    switch {
    case score >= 90:
        fmt.Println("good")
    case score >= 80 && score < 90:
        fmt.Println("well")
    case score < 80:
        fmt.Println("ok")
    }
}
// 请输入成绩:60
// ok

// 请输入成绩:85
// well

summary

Go rarely used language usually write switch statements, sometimes suddenly use, some details may be forgot, so writing a blog summary.

Guess you like

Origin www.cnblogs.com/yahuian/p/11615408.html