if switch

  1. if

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    const filename = "a.txt"
    contents,err :=ioutil.ReadFile(filename)
    if err != nil {
    fmt.Println(err)
    }else {
    fmt.Printf("%s",contents)
    }

    //简写版本
    const filename = "a.txt"
    if contents,err :=ioutil.ReadFile(filename) ; err != nil {
    fmt.Println(err)
    }else {
    fmt.Printf("%s",contents)
    }
    //只在if 作用域内

  2. switch

    switch 默认带上braek 除非显式指定fallthrough

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    var res int
    switch op {
    case "+":
    res = a+b
    case "-":
    res = a-b
    case "*":
    res = a*b
    case "/":
    res = a/b
    fallthrough
    case "p":
    fmt.Println("hello")
    default:
    panic("undefine opcode:" + op)
    }
    fmt.Println(res)
    //hello
    //0
    //不携带参数
    var res int
    flag := rand.Int()
    switch {
    case op == "+":
    res = a + b
    case flag > 10000:
    res = 1
    //...
    }
    fmt.Println(res)