funcmain() { score := 80 switch { case score >= 90:fmt.Println("优秀") case score >= 80:fmt.Println("良好") case score >= 70:fmt.Println("一般") default:fmt.Println("默认") } }
当case为表达式时,则switch中就不需要再写变量。
运行结果:
fallthrough
由于在go语言中每一个case后面都会默认加上break,所以每次匹配都执行其中的一个case,但是如果需要执行后面的case,则可以使用fallthrough,使用 fallthrough 会强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true。
代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package main
import"fmt"
funcmain() { score := 80 switch { case score >= 90: fmt.Println("优秀") fallthrough case score >= 80: fmt.Println("良好") fallthrough case score >= 70: fmt.Println("一般") fallthrough default:fmt.Println("默认") } }