【Go】18、golang switch语句

  • go语言中的switch语句,可以非常容易的判断多个值的情况
  • go里面switch默认相当于每个case最后带有break,匹配成功后不会自动向下执行其他case,而是跳出整个switch
  • fallthrough强制执行后面的case代码[加了fallthrough后,会直接运行【紧跟的后一个】case或default语句,不论条件是否满足都会执行]
  • fallthrouth不能用到switch的最后一个分支
1、go语言中switch语句的语法
switch var1 {
    case val1:
    	...
    case val2:
    	...
    default:
    	...
}
2、go语言中switch语句实例
  • 判断成绩
func test1() {
	// 判断成绩
	grade := 'A'

	switch grade {

	case 'A':
		fmt.Println("A")
	case 'B':
		fmt.Println("B")
	case 'C':
		fmt.Println("C")
	default:
		fmt.Println("D")
	}
}

func main() {
	test1()
}
# 输出结果:
    A
  • 多条件匹配
    • go语言switch语句,可以同时匹配多个条件,中间用逗号分隔,有其中一个匹配成功即可
func test2() {
	day := 3
	switch day {
	case 1, 2, 3, 4, 5:
		fmt.Println("正常班")
	default:
		fmt.Println("周末啦")
	}
}

func main() {
	test2()
}
# 输出结果
    正常班
  • case也可以是条件表达式:switch后不跟表达式,默认为true
func test3() {
	// case 也可以是条件表达式
	score := 90

	switch {
	case score >= 60 && score < 70:
		fmt.Println("及格")
	case score >= 70 && score < 80:
		fmt.Println("良")
	case score >= 80 && score < 90:
		fmt.Println("较好")
	default:
		fmt.Println("优秀")
	}
}

func main() {
	test3()
}
# 输出结果
	优秀
  • fallthrough执行下一个case
func test4() {
	// fallthrough可以执行满足条件的下一个case
	a := 100

	switch {
	case a == 100:
		fmt.Println("a")
		fallthrough
	case a == 200:
		fmt.Println("b")
	case a == 300:
		fmt.Println("c")
	default:
		fmt.Println("d")
	}
}

func main() {
	test4()
}
# 输出结果
	100 
	200
3、go语言中switch语句的注意事项
  • 支持多条件匹配
  • 不同的case之间不使用break分隔,默认只会执行一个case
  • 如果想要执行多个case,需要使用fallthrough关键字,也可用break终止
  • 分支还可以使用表达式,例如:a>10
posted @ 2022-06-15 14:47  郭祺迦  阅读(673)  评论(0)    收藏  举报