4.2 Go switch

4.2 Go switch

switch statement based on different conditions to perform different actions, each unique branch case, the top-down individually tested until the end of the match, the default 自动终止, 不需要break.

2. switch basic grammar

  1. Followed later switch expression (variables, constants, functions, and so the return value)
  2. The latter case must be consistent expression and expression data type switch
  3. You can have multiple expressions after the case
  4. case behind the constant expression must not be repeated
package main

import "fmt"

func main() {
    var week int
    fmt.Println("请输入星期几:")
    fmt.Scanln(&week)

    switch week {
    case 1:
        fmt.Println("星期一,上班!!")
    case 2, 3, 4, 5:
        fmt.Println("星期二到星期五,你还得上班!!")
    case 6:
        fmt.Println("周六你就想休息?加班!!")
    case 7:
        fmt.Println("老子迟早要辞职,终于能休息了!!")
    default:
        fmt.Println("输入错误你就必须得上班!!")
    }
}
  1. Alternatively switch using if-else
package main

import "fmt"

func main() {
    var score int
    fmt.Println("请录入你的成绩:>")
    fmt.Scanln(&score)
    switch {
    case score > 90:
        fmt.Println("成绩优秀")
    case score >= 70:
        fmt.Println("及格中等")
    case score >= 60:
        fmt.Println("勉强及格了")
    default:
        fmt.Println("恭喜你,考试不及格")
    }
}
  1. switch of penetration fallthrough, after the case statement added fallthrough block will proceed to the next case
package main

import "fmt"

func main() {
    var score int
    fmt.Println("请录入你的成绩:>")
    fmt.Scanln(&score)
    switch {
    case score > 90:
        fmt.Println("成绩优秀")
        fallthrough
    case score >= 70:
        fmt.Println("及格中等")
    case score >= 60:
        fmt.Println("勉强及格了")
    default:
        fmt.Println("恭喜你,考试不及格")
    }
}

7.switch may also be used a variable type variable determining interface actually stored.

package main

import "fmt"

func main() {
    var x interface{} //x是空接口类型,可以接收任意类型
    var y = 19.9
    x = y
    switch i := x.(type) {
    case nil:
        fmt.Printf("x的类型是%T\n", i)
    case float64:
        fmt.Printf("x的类型是%T\n", i)
    default:
        fmt.Println("未知类型")
    }
}

2.1. switch和if

Analyzing few specific values, match type integer, floating point, character, character string, etc., it is recommended switch.

Analyzing of bool type, with if, if a wider range of controllable.

Guess you like

Origin www.cnblogs.com/open-yang/p/11256802.html