每天五分钟Go - 条件语句
if语句
if 布尔表达式 {
/* 在布尔表达式为 true 时执行 */
} else {
/* 在布尔表达式为 false 时执行 */
}
如下代码
if a>10{
fmt.Println("大于10")
}else if a>5 && a<=10{
fmt.Println("小于等于10 大于5")
}else{
fmt.Println("小于5")
}
switch语句
switch [var1] {
case val1:
...
case val2:
...
default:
...
}
和java语言不一的地方是case里面没有break
的关键词,更神奇的地方是 switch后面的变量可以省略
switch a {
case 10:
fmt.Println("厉害")
case 20:
fmt.Println("更厉害")
case 30:
fmt.Println("超神了")
case 0:
fmt.Println("渣渣了")
default:
fmt.Println("无fuck说")
}
switch {
case a==10:
fmt.Println("厉害")
case a==20:
fmt.Println("更厉害")
case a==30:
fmt.Println("超神了")
case a==0:
fmt.Println("渣渣了")
default:
fmt.Println("无fuck说")
}
显然,还是switch后面跟着变量比较省事
走后门的fallthrough
fallthrough
会强制执行后面的 case 语句,fallthrough
不会判断下一条 case 的表达式结果是否为 true
switch {
case true:
fmt.Println("我打印了")
fallthrough
case false:
fmt.Println("我走后门了")
fallthrough
default:
fmt.Println("我也打印了")
}