switch语句
Go里面switch默认相当于每个case最后带有break,匹配成功后不会自动向下执行其他case,
而是跳出整个switch, 但是可以使用fallthrough强制执行后面的case代码:
var num int
fmt.Printf("请输入楼层:")
fmt.Scan(&num)
switch num {
case 1:
fmt.Println("按下的是1楼")
break //go语言保留了break关键字,跳出switch语句, 不写,默认就包含
case 2:
fmt.Println("按下的是2楼")
fallthrough //不跳出switch语句,后面的无条件执行
case 3:
fmt.Println("按下的是3楼")
// fallthrough
default:
fmt.Println("按下的是xxx楼")
}
结果:

可以使用任何类型或表达式作为条件语句:
//1
switch s1 := 90; s1 { //初始化语句;条件
case 90:
fmt.Println("优秀")
case 80:
fmt.Println("良好")
default:
fmt.Println("一般")
}
//2
var s2 int = 90
switch { //这里没有写条件
case s2 >= 90: //这里写判断语句
fmt.Println("优秀")
case s2 >= 80:
fmt.Println("良好")
default:
fmt.Println("一般")
}
//3
switch s3 := 90; { //只有初始化语句,没有条件
case s3 >= 90: //这里写判断语句
fmt.Println("优秀")
case s3 >= 80:
fmt.Println("良好")
default:
fmt.Println("一般")
}
以上。
朱子家训说:宜未雨而筹谋,勿临渴而掘井。
任何事情要到了跟前才想解决办法,那我们岂不很被动!

浙公网安备 33010602011771号