美文网首页深入浅出golang程序员Golang
golang 基础(7)条件语句

golang 基础(7)条件语句

作者: zidea | 来源:发表于2019-03-16 16:39 被阅读26次
    images.png

    条件语句

    if 语句

    if true {
        fmt.Println("this is true)
    }
    
    func bounded(num int) int {
        if num > 100 {
            return 100
        }else if num < 0 {
            return 0
        }else{
            return 0
        }
    }
    

    if 的条件里不需要括号的

    • 引入用于读取文件的io/ioutil标准库
    func main()  {
        const filename = "abc.txt"
        body, err := ioutil.ReadFile(filename)
        if err != nil{
            fmt.Println(err)
        }else{
            fmt.Printf("%s\n",body)
        }
    }
    

    ioutil.ReadFile(filename) 这个函数返回两个值,分别是 []byte 和 error,go 语言中是可以返回两个值

    因为我们还没有创建 abc.txt 文件所以会报错

    open abc.txt: The system cannot find the file specified
    

    我们也可以在 go 中将上面表达式进行简化,将表达式写入if语句

    if body, err := ioutil.ReadFile(filename); err != nil {
            fmt.Println(err)
        }else{
            fmt.Printf("%s\n",body)
        }
    

    我们在 if 代码块以外是无法访问到 body error 变量

    b := true
        if food := "chocolate"; b {
            fmt.Println(food)
        }
    

    if 其实为我们提供一个作用域,

    switch 语句

    go 中 switch 不需要为分支语句加 break,除非使用 fallthrough

    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
    }
    

    fmt.Println(
    grade(0),
    grade(85),
    grade(120),
    )

    这里注意一下这里 grade(120) 也是需要以(逗号,) 结尾的,不然编译期间报错,因为我们结尾 ) 换行了,如果不换行就不需要 grade(120) 后面加 (逗号,)

    因为 120 不是取值范围,所以报错并且其他值也没有计算出来。panic 会中断程序

    panic: Wrong score: 120
    
    Golang1.png

    相关文章

      网友评论

        本文标题:golang 基础(7)条件语句

        本文链接:https://www.haomeiwen.com/subject/xcusmqtx.html