Go语言学习之——switch

根据传入条件的不同,选择语句会执行不同的语句。下面的例子根据传入的整型变量i的不同而打印不同的内容:

switch i { 
    case 0: 
        fmt.Printf("0") 
    case 1: 
        fmt.Printf("1") 
    case 2: 
        fallthrough 
    case 3: 
        fmt.Printf("3") 
    case 4, 5, 6: 
        fmt.Printf("4, 5, 6") 
    default: 
        fmt.Printf("Default") 
} 

switch后面可以没有表达式

package main

import (
    "io/ioutil"
    "fmt"
)

func grade(score int) string{
    var g string

    switch {
    case score < 0 || score > 100:
        panic( fmt.Sprintf("Wrong Score:%d", score) ) //panic会中断程序,它的输入是字符串,fmt.Sprintf的作用的是拼接生成一个字符串,但不会打印出来。
    case score < 60:
        g = "F"
    case score < 70:
        g = "D"
    case score < 80:
        g = "C"
    case score < 90:
        g = "B"
    case score <= 100:
        g = "A"
    //default:
    //  panic( fmt.Sprintf("Wrong Score:%d", score) )
    }

    return g
}

func main() {
    const filename = "test.txt"

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

    fmt.Println(
        grade(0),
        grade(30),
        grade(66),
        grade(76),
        grade(89),
        grade(90),
        grade(100),
        grade( 103 ), //注意这里有个逗号
        //output:panic: Wrong Score:103,因为panic会中断,整个fmt.Println被中断,所以前面的几个grade函数的结果不会打印,但是并不影响if else里面的打印,如果几个println是拆开写的,前面的grade的结果就会打印出来。
        )
}

你可能感兴趣的:(Go语言学习之——switch)