軌道
/
Go
Go
/
課程大綱
/
switch 條件式
sw

switch 條件式 在 Go

1 個練習

關於 switch 條件式

switch敘述會對一個運算式求值,並執行第一個符合其值的case。 比起一長串的if ... else if,它通常是更簡潔的做法。

基本用法

operatingSystem := "windows"

switch operatingSystem {
case "windows":
    // do something if the operating system is windows
case "linux":
    // do something if the operating system is linux
case "macos":
    // do something if the operating system is macos
default:
    // do something if the operating system is none of the above
}

多個值可以用逗號分組到同一個case。 只要運算式等於其中任何一個值,這個case就會符合:

switch operatingSystem {
case "windows", "linux":
    // do something if the operating system is windows or linux
case "macos":
    // do something if the operating system is macos
default:
    // do something if the operating system is none of the above
}

無運算式的 switch

switch後面的運算式也可以整個省略。 此時每個case會帶有一個布林運算式,第一個求值結果為true的就會執行。

age := 21

switch {
case age > 20 && age < 30:
    // do something if age is between 20 and 30
case age == 10:
    // do something if age is equal to 10
default:
    // do something else for every other case
}

初始化敘述

和if一樣,switch可以在運算式前面加上一段簡短的初始化敘述。 在那裡宣告的變數,作用域僅限於這個switch程式區塊:

switch v := getValue(); {
case v < 0:
    // do something if v is less than 0
case v == 0:
    // do something if v is 0
default:
    // do something else for every other case
}
// v will not be accessible here

fallthrough

fallthrough會讓下一個 case 的本體執行,不論它的運算式是否符合。 它必須是該 case 本體中的最後一個敘述,而且後面必須還有下一個 case 可以執行。

在道地的 Go 程式碼中,fallthrough並不常見,因為它會讓相鄰的 case 彼此相依。 如此一來,就很難單獨推敲每個 case,讓整個 switch 更難閱讀。 當多個 case 應該有相同的行為時,用逗號把它們分組會更清楚。 當邏輯因為其他原因而需要在多個 case 之間共用時,可以考慮把共用的邏輯抽成一個輔助函式。

s := "hello"

switch s {
case "hello":
    fmt.Println("hello")
    fallthrough
case "world":
    fmt.Println("world") // also runs, even though s != "world"
}
// Output:
// hello
// world

想進一步了解,可以參考 Go by Example: Switch 或 Go 語言規格。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 switch 條件式