Go Wiki: Switch
規範: https://golang.com.tw/ref/spec#Switch_statements
Go 的 switch 語句非常巧妙。首先,你不需要在每個 case 的末尾使用 break。
switch c {
case '&':
esc = "&"
case '\'':
esc = "'"
case '<':
esc = "<"
case '>':
esc = ">"
case '"':
esc = """
default:
panic("unrecognized escape character")
}
不只是整數
Switch 可以處理任何型別的值。
switch syscall.OS {
case "windows":
sd = &sysDir{
Getenv("SystemRoot") + `\system32\drivers\etc`,
[]string{
"hosts",
"networks",
"protocol",
"services",
},
}
case "plan9":
sd = &sysDir{
"/lib/ndb",
[]string{
"common",
"local",
},
}
default:
sd = &sysDir{
"/etc",
[]string{
"group",
"hosts",
"passwd",
},
}
}
缺失的表示式
實際上,你甚至不需要 switch 任何東西。一個沒有值的 switch 意味著“switch true”,使其成為 if-else 鏈的一個更簡潔的版本,就像 Effective Go 中的這個例子一樣。
func unhex(c byte) byte {
switch {
case '0' <= c && c <= '9':
return c - '0'
case 'a' <= c && c <= 'f':
return c - 'a' + 10
case 'A' <= c && c <= 'F':
return c - 'A' + 10
}
return 0
}
Break
Go 的 switch 語句會隱式地 break,但 break 仍然有用。
command := ReadCommand()
argv := strings.Fields(command)
switch argv[0] {
case "echo":
fmt.Print(argv[1:]...)
case "cat":
if len(argv) <= 1 {
fmt.Println("Usage: cat <filename>")
break
}
PrintFile(argv[1])
default:
fmt.Println("Unknown command; try 'echo' or 'cat'")
}
Fall through
要 fall through 到後續的 case,請使用 fallthrough 關鍵字。
v := 42
switch v {
case 100:
fmt.Println(100)
fallthrough
case 42:
fmt.Println(42)
fallthrough
case 1:
fmt.Println(1)
fallthrough
default:
fmt.Println("default")
}
// Output:
// 42
// 1
// default
另一個例子
// Unpack 4 bytes into uint32 to repack into base 85 5-byte.
var v uint32
switch len(src) {
default:
v |= uint32(src[3])
fallthrough
case 3:
v |= uint32(src[2]) << 8
fallthrough
case 2:
v |= uint32(src[1]) << 16
fallthrough
case 1:
v |= uint32(src[0]) << 24
}
src/pkg/encoding/ascii85/ascii85.go
‘fallthrough’ 必須是 case 中的最後一項;你不能寫成這樣:
switch {
case f():
if g() {
fallthrough // Does not work!
}
h()
default:
error()
}
但是,你可以透過使用“帶標籤的” fallthrough 來解決這個問題。
switch {
case f():
if g() {
goto nextCase // Works now!
}
h()
break
nextCase:
fallthrough
default:
error()
}
注意:fallthrough 在 type switch 中不起作用。
多個 case
如果你想在同一個 case 中使用多個值,請使用逗號分隔的列表。
func letterOp(code int) bool {
switch chars[code].category {
case "Lu", "Ll", "Lt", "Lm", "Lo":
return true
}
return false
}
Type switch
使用 type switch,你可以根據介面值的型別進行 switch(僅限於此)。
func typeName(v interface{}) string {
switch v.(type) {
case int:
return "int"
case string:
return "string"
default:
return "unknown"
}
}
你還可以宣告一個變數,它將具有每個 case 的型別。
func do(v interface{}) string {
switch u := v.(type) {
case int:
return strconv.Itoa(u*2) // u has type int
case string:
mid := len(u) / 2 // split - u has type string
return u[mid:] + u[:mid] // join
}
return "unknown"
}
do(21) == "42"
do("bitrab") == "rabbit"
do(3.142) == "unknown"
Noop case
有時,擁有不需要執行任何操作的 case 是很有用的。這看起來可能會令人困惑,因為它可能看起來像是 noop case 和後續 case 具有相同的操作,但實際上並非如此。
func pluralEnding(n int) string {
ending := ""
switch n {
case 1:
default:
ending = "s"
}
return ending
}
fmt.Sprintf("foo%s\n", pluralEnding(1)) == "foo"
fmt.Sprintf("bar%s\n", pluralEnding(2)) == "bars"
此內容是 Go Wiki 的一部分。