知识点
go语言中的switch
语句,类似c语言,但是,每一个case最后的结束默认为break
,所以可以省略。
另外,go语言中增加了一个fallthrough
关键字,该关键字表示不跳出case语句,带上后等价于c语言没带break
语句的情况,不常用。
具体用法有三种:
1、普通switch语句
2、带赋值语句的switch语句
3、不带变量的switch语句,将条件放入case语句中,更加灵活。
package main
import "fmt"
func main() {
var num int
fmt.Println("请输入数字:")
fmt.Scan(&num)
switch num { // switch关键字后接变量
case 1:
fmt.Println("1") // 不需要break语句,case语句默认包含了break语句,写不写都行
case 2:
fmt.Println("2")
fallthrough //该关键字表示不跳出case语句,这样后面的case 3也会被执行。
case 3:
fmt.Println("3")
case 4:
fmt.Println("4")
default:
fmt.Println("other")
}
// switch语句跟if语句一样,支持单变量初始化,或者平行初始化
switch num := 1; num {
case 1:
fmt.Println("1")
case 2:
fmt.Println("2")
}
// 可以不带条件,更加灵活
score := 85
// 可以不带条件,更加灵活
switch {
case score > 90:
fmt.Println("A")
case score > 80:
fmt.Println("B")
case score > 60:
fmt.Println("C")
}
}