Golang學習筆記(八)switch分支語句
阿新 • • 發佈:2018-11-05
Golang的switch可以不用在每個case裡寫一個break,Golang會自動加入。
default關鍵字可以帶,也可以不帶,不是必須要有的。
首先是一個最基礎的示例,在switch後面帶一個變數。
func ScoreGrade1() { gradel := "B" switch gradel { case "A": fmt.Println("優秀") case "B": fmt.Println("良好") case "C": fmt.Println("中等") case "D": fmt.Println("及格") default: fmt.Println("不及格") } }
接著是一個switch後面不帶變數的,如果沒有帶變數,實際switch後面是一個true,只要case後面成立即可。
func ScoreGrade2() { score := 58.5 switch { case score >= 90: fmt.Println("優秀") case score >= 80: fmt.Println("良好") case score >= 70: fmt.Println("中等") case score >= 60: fmt.Println("及格") default: fmt.Println("不及格") } }
每個case的條件可以是一個,也可以是多個,多個條件用“,”來隔開,給出一個示例,計算某年某月有多少天。
func Days() { year := 2008 month := 2 days := 0 switch month { case 1, 3, 5, 7, 8, 10, 12: days = 31 case 4, 6, 9, 11: days = 30 case 2: if year%4 == 0 { days = 29 } else { days = 28 } default: days = -1 } fmt.Println("一共有:", days, "天") }
switch的case裡,有一個fallthrough的關鍵字,他使得case執行完以後,強制執行下面一個case。
func Fallthrough(){
num := 10
switch {
case num >= 5 :
fmt.Println("數值大於5")
fallthrough
case num >= 6 :
fmt.Println("數值大於6")
fallthrough
case num >= 7 :
fmt.Println("數值大於7")
case num >= 8 :
fmt.Println("數值大於8")
case num >= 9 :
fmt.Println("數值大於9")
}
}
原本沒有fallthrough關鍵字,執行到數值大於5後,就結束。
加入後,將執行到數值大於7。
PS:switch在滿足最上面的case後即跳轉,如上一篇文章中的分數查詢的判斷,也必須由大至小的給出case條件