switch 变量 {
case 常量1:
...
case 常量2:
...
default:
...
}
例子:有判断变量的switch条件判断
package main
import (
"fmt"
)
func main() {
switchColor("red")
switchColor("yellow")
switchColor("blue")
switchColor("black")
}
func switchColor(color string) {
// 通过switch语句判断不同color时的输出信息
switch color {
case "yellow":
fmt.Println("banana is yellow.")
// 使用fallthrough可以连带执行下一个case体中的逻辑
fallthrough
case "red":
fmt.Println("apple is red.")
case "blue":
fmt.Println("sky is blue.")
// 使用break跳出switch体
if true {
break
}
fmt.Println("you will never see me ")
default:
fmt.Println("i have no idea what color it is.")
}
}
以上代码的执行结果:
apple is red.
banana is yellow.
apple is red.
sky is blue.
i have no idea what color it is.