1 定义
switch语句是选择分支
语法
switch expr {
case x:{
// 选择体
}
case x+1 :{
// 选择体
}
default: {
// 默认体
}
}
2 switch实例
package main
import "fmt"
func main() {
week := 6
switch week {
case 0:
{
fmt.Println("今天星期天")
}
case 1:
{
fmt.Println("今天星期一")
}
case 2:
{
fmt.Println("今天星期二")
}
case 3:
{
fmt.Println("今天星期三")
}
case 4:
{
fmt.Println("今天星期四")
}
case 5:
{
fmt.Println("今天星期五")
}
case 6:
{
fmt.Println("今天星期六")
}
default:
{
fmt.Println("无效数字")
}
}
}
3 case后面多表达式
package main
import "fmt"
func main() {
week := 5
switch week {
case 0:
{
fmt.Println("今天星期天")
}
case 1, 2, 3, 4, 5:
{
fmt.Println("今天工作日")
}
case 6:
{
fmt.Println("今天星期六")
}
default:
{
fmt.Println("无效数字")
}
}
}
4 无表达式的switch
无表达式的switch会判断所有的case
package main
import "fmt"
func main() {
scores := 75
switch {
case scores > 0 && scores < 60:
{
fmt.Println("不及格")
}
case scores >= 60 && scores < 80:
{
fmt.Println("及格")
}
case scores >= 80 && scores < 100:
{
fmt.Println("无效数字")
}
}
}
5 fallthrough 语句用法
switch语句,匹配到一个case之后,switch语句就结束了。
fallthrough语句在case中,只能在case中的最后一行。并且穿透这个case,继续往下匹配
package main
import "fmt"
func main() {
scores := 70
switch {
case scores >= 0 && scores < 60:
fmt.Println("不合格!!!")
case scores >= 60 && scores < 70:
fmt.Println("良好")
fallthrough
case scores >= 60 && scores < 80:
fmt.Println("优秀")
fallthrough
default:
fmt.Println("默认。。。")
}
}