和其他語言一樣,Go 也提供了switch敘述。
switch敘述是撰寫冗長的if ... else if敘述時更簡潔的方式。
要建立一個 switch,我們會先使用關鍵字switch,後面接著一個值或運算式。
接著,我們會用case關鍵字宣告每一個條件。
我們也可以宣告一個default case,當前面所有case條件都不符合時,它就會執行:
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
}
switch 敘述有一個有趣的地方:switch關鍵字後面的值可以省略,而且我們可以為每個case設定布林條件:
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
}
在這個練習中,我們會模擬一場 Blackjack 遊戲的第一回合。
你會收到兩張牌,並能看到莊家掀開的那張牌。 所有牌都用字串表示,例如 "ace"、"king"、"three"、"two" 等。 每張牌的點數如下:
| 牌 | 點數 | 牌 | 點數 |
|---|---|---|---|
| ace | 11 | eight | 8 |
| two | 2 | nine | 9 |
| three | 3 | ten | 10 |
| four | 4 | jack | 10 |
| five | 5 | queen | 10 |
| six | 6 | king | 10 |
| seven | 7 | 其他 | 0 |
注意:一般來說,ace 可以算作 1 或 11,但為了簡單起見,我們假設它只能算作 11。
根據你的兩張牌和莊家的牌,遊戲的第一回合有一套策略,其中你有以下選項:
雖然還不是最佳策略,但你要遵循你的朋友 Alex 一直在開發的策略,內容如下:
實作一個函式,用來計算一張牌的數值:
value := ParseCard("ace")
fmt.Println(value)
// Output: 11
撰寫一個函式,實作上述的決策邏輯:
func FirstTurn(card1, card2, dealerCard string) string
以下是幾個預期結果的範例:
FirstTurn("ace", "ace", "jack") == "P"
FirstTurn("ace", "king", "ace") == "S"
FirstTurn("five", "queen", "ace") == "H"