美文网首页
Go条件语句

Go条件语句

作者: MrSYLong | 来源:发表于2018-08-19 22:05 被阅读11次
    package main
    
    import (
        "io/ioutil"
        "fmt"
    )
    
    // switch语句
    // switch会自动break 除非使用fallthrough
    // switch后可以没有表达式
    func eval(a, b int, op string) int {
        var reslut int
        switch op {
        case "+":
            reslut = a + b
        case "-":
            reslut = a - b
        case "*":
            reslut = a * b
        case "/":
            reslut = a / b
        default:
            panic("unsupported operator:"+op)
        }
        return reslut
    }
    
    func grade(soure int) string {
        g := ""
        switch {
        case soure < 60:
            g = "F"
        case soure < 80:
            g = "C"
        case soure < 90:
            g = "B"
        case soure < 100:
             g = "A"
        case soure < 0 || soure > 100:
            panic(fmt.Sprintf("wrong soure : %d", soure))
        }
        return g
    }
    
    
    func main() {
    
        // if语句
        // if的条件里不需要括号
        // if的条件里可以赋值
        // if的条件里赋值的变量作用域就在这个if语句里
        const filename =  "abc.txt"
    
        contents, err := ioutil.ReadFile(filename)
        if err != nil {
             fmt.Println(err)
        } else {
            fmt.Printf("%s\n",contents)
        }
    
        if contents, err := ioutil.ReadFile(filename); err != nil {
            fmt.Println(err)
        } else  {
            fmt.Printf("%s\n",contents)
        }
    
    
        fmt.Println(grade(50), grade(70), grade(85), grade(95))
        //fmt.Println(grade(-5), grade(105))
    }
    

    相关文章

      网友评论

          本文标题:Go条件语句

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