Golang: switch case 與 fallthrough

Golang: switch case 與 fallthrough

Exmaple:

package main

import "fmt"

func main() {
	handle(0)
	handle(1)
}

func handle(i int) {
	switch i {
		case 0:
		case 1:
			fallthrough
		case 2:
			fmt.Println("2")
		case 3:
			fmt.Println("3")
	}
}

輸出:

2

結論:

  • Golang 在執行完每個 case 後會自動跳出 switch 語句塊,即使是空的 case。
  • fallthrough 指示去執行下一個 case 的語句塊(case 2),不會運行到(case 3)。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章