只执行选择的 case 所以不需要 break 语句,case 判断可以是变量
package main
import ( "fmt" "runtime" )
func main() { fmt.Print("Go runs on ") switch os := runtime.GOOS; os { case "darwin": fmt.Println("OS X.") case "linux": fmt.Println("Linux.") default: fmt.Printf("%s.\n", os) } }
|
switch和java,c等的有不同的地方,使用上需要注意
不需要使用break,默认每个case是独立执行的
switch ch { case '0': cl = "Int" case '1': cl = "Int" case 'A': cl = "ABC" break case 'a': cl = "ABC" default: cl = "Other Char" }
|
需要执行下一条case的情况,使用 fallthrough 语句,’0’和’1’都会执行cl=”Int”。
switch ch { case '0': fallthrough case '1': cl = "Int" case 'A': case 'a': fallthrough cl = "ABC" default: cl = "Other Char" }
|
有多个匹配结果执行同一段处理的情况
switch ch { case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': cl = "Int" case 'A', 'B', 'C', 'D', 'a', 'b', 'c', 'd', 'e': cl = "ABC" default: cl = "Other Char" }
|
在 Case 中使用布尔表达式
switch { case '0' <= ch && ch <= '9': cl = "Int" case ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'): cl = "ABC" default: cl = "Other Char" }
|