go的switch case

可以一個case帶幾個參數:

var i = 0
switch i {
case 0, 1:
      fmt.Println(“1”)
case 2:
fmt.Println(“2”)
default:
     fmt.Println(“def”)
}

默認有break效果,要取消就加上fallthrough:

var i = 0
switch i {
case 0:
        fallthrough
case 1:
      fmt.Println(“1”)
case 2:
fmt.Println(“2”)
default:
     fmt.Println(“def”)
}

case還可以是表達式:

var i = 0
switch {
case i > 0 && i < 10:
      fmt.Println(“i > 0 and i < 10”)
case i > 10 && i < 20:
fmt.Println(“i > 10 and i < 20”)
default:
     fmt.Println(“def”)
}

注意:go的switch case默認有break。如果不需要break,可以加上fallthrough**~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章