一、IF语句

package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    const filename = "abc.txt"
    contents, err := ioutil.ReadFile(filename)

    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("%s\n", contents)
    }
}

if语句还可以类似for的写法

func main() {
    const filename = "abc.txt"
    if contents, err := ioutil.ReadFile(filename); err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("%s\n", contents)
    }

}
因为contentserr是在if语句中定义的,所以作用范围只在if语句内,外面无法访问
  1. if的条件里可以赋值
  2. if的条件里赋值的变量作用域就在这个if语句里

二、SWITCH语句

  1. switch会自动 break,除非使用 fallthrough
  2. switch 后可以没有表达式
package main

import (
    "fmt"
    "io/ioutil"
)

func grade(score int) string {
    g := ""
    switch score {
    case 90:
        g = "A"
    case 80:
        g = "B"
    case 50, 60, 70:
        g = "C"
    default:
        g = "D"
    }

    return g
}

func main() {
    fmt.Println(
        grade(0),
        grade(59),
        grade(60),
        grade(70),
        grade(80),
        grade(1111),
    )
}

switch 后没有表达式

package main

import (
    "fmt"
    "io/ioutil"
)

func grade(score int) string {
    g := ""
    switch {
    case score < 0 || score > 100:
        panic(fmt.Sprintf("Wrong score: %d", score))
    case score < 60:
        g = "F"
    case score < 80:
        g = "C"
    case score < 90:
        g = "B"
    case score <= 100:
        g = "A"
    }
    return g
}

func main() {
    fmt.Println(
        grade(0),
        grade(59),
        grade(60),
        grade(70),
        grade(80),
        grade(1111),
    )
}