GO语言-基础语法:条件判断

1. IF判断(aa.txt内容:asdfgh。bb.txt内容:12345)

package main

import (
    "io/ioutil"
    "fmt"
)

func main() {
    const filename1, filename2 = "aa.txt", "bb.txt"

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

    fmt.Printf("%s\n", contents) //打印出filename1的内容

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

    fmt.Printf("%s\n", contents) //还是打印出filename1的内容,filename2在if条件内,跳出IF之后失效(IP内部赋值,只对本次IF有效)
}

打印结果;

asdfgh
asdfgh
12345
asdfgh
[Finished in 0.6s]

 2. switch

package main

import (
    "fmt"
)

//定义函数:grade:函数名。score:传入的变量,类型是int。string:函数返回的类型。
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"
    default://在本次switch中可以不写default,因为第一个case已经判断了所以的异常
         panic(fmt.Sprintf(
             "Wrong score: %d", score))
    }

    return g
}

func main() {
    fmt.Println(grade(50),grade(60),grade(90),grade(10))
}

打印结果:

F C A F
[Finished in 0.7s]

 

posted on 2018-08-14 15:21  vijayfly  阅读(357)  评论(0编辑  收藏  举报

导航