Go 語言中的 switch 語句
Go 語言中的 switch
語句
正如代碼清單 3-6 所示,Go 提供了 switch
語句,它可以將一個值和多個值進行比較。
代碼清單 3-6 switch
語句: concise-switch.go
fmt.Println("There is a cavern entrance here and a path to the east.") var command = "go inside" switch command { // 將命令和給定的多個分支進行比較 case "go east": fmt.Println("You head further up the mountain.") case "enter cave", "go inside": // 使用逗號分隔可選值 fmt.Println("You find yourself in a dimly lit cavern.") case "read sign": fmt.Println("The sign reads 'No Minors'.") default: fmt.Println("Didn't quite get that.") }
執行這個程序將產生以下輸出:
There is a cavern entrance here and a path to the east. You find yourself in a dimly lit cavern.
Note
除了文字以外, switch
語句還可以接受數字作爲條件。
switch
的另一種用法是像 if...else
那樣,在每個分支中單獨設置比較條件。 正如代碼清單 3-7 所示, switch
還擁有獨特的 fallthrough
關鍵字,它可以用於執行下一分支的代碼。
代碼清單 3-7 switch
語句: switch.go
var room = "lake" switch { // 比較表達式將被放置到單獨的分支裏面。 case room == "cave": fmt.Println("You find yourself in a dimly lit cavern.") case room == "lake": fmt.Println("The ice seems solid enough.") fallthrough // 下降(fall through)至下一分支。 case room == "underwater": fmt.Println("The water is freezing cold.") }
執行這段代碼將產生以下輸出:
The ice seems solid enough. The water is freezing cold.
Note
在 C、Java、JavaScript 等語言中, 下降是 switch
語句各個分支的默認行爲。 Go 對此採取了更爲謹慎的做法, 用戶需要顯式地使用 fallthrough
關鍵字纔會引發下降。