switch 变量 {
case 常量1:
...
case 常量2:
...
default:
...
}
例子:有判断变量的switch条件判断
packagemainimport ("fmt")funcmain() {switchColor("red")switchColor("yellow")switchColor("blue")switchColor("black")}funcswitchColor(color string) {// 通过switch语句判断不同color时的输出信息switch color {case"yellow": fmt.Println("banana is yellow.")// 使用fallthrough可以连带执行下一个case体中的逻辑fallthroughcase"red": fmt.Println("apple is red.")case"blue": fmt.Println("sky is blue.")// 使用break跳出switch体iftrue {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.