扫码一下
查看教程更方便
switch 语句用于基于不同条件执行不同动作,每一个 case 分支都是唯一的,从上至下逐一测试,直到匹配为止。
switch 语句执行的过程从上至下,直到找到匹配项,匹配项后面也不需要再加 break。
switch 默认情况下 case 最后自带 break 语句,匹配成功后就不会执行其他 case,如果我们需要执行后面的 case,可以使用 fallthrough 。
go 编程语言中 switch 语句的语法如下:
switch var1 {
case val1:
...
case val2:
...
default:
...
}
变量 var1 可以是任何类型,而 val1 和 val2 则可以是同类型的任意值。类型不被局限于常量或整数,但必须是相同的类型;或者最终结果为相同类型的表达式。
您可以同时测试多个可能符合条件的值,使用逗号分割它们,例如:case val1, val2, val3。
流程图:
package main
import "fmt"
func main() {
var grade string = "b"
var marks int = 90
switch marks {
case 90: grade = "a"
case 80: grade = "b"
case 50,60,70 : grade = "c"
default: grade = "d"
}
switch {
case grade == "a" :
fmt.printf("excellent!\n" )
case grade == "b", grade == "c" :
fmt.printf("well done\n" )
case grade == "d" :
fmt.printf("you passed\n" )
case grade == "f":
fmt.printf("better try again\n" )
default:
fmt.printf("invalid grade\n" );
}
fmt.printf("your grade is %s\n", grade );
}
上述代码编译执行结果如下
excellent!
your grade is a
switch 语句还可以被用于 type-switch 来判断某个 interface 变量中实际存储的变量类型。
type switch 语法格式如下:
switch x.(type){
case type:
statement(s);
case type:
statement(s);
/* 你可以定义任意个数的case */
default: /* 可选 */
statement(s);
}
package main
import "fmt"
func main() {
var x interface{}
switch i := x.(type) {
case nil:
fmt.printf("type of x :%t",i)
case int:
fmt.printf("x is int")
case float64:
fmt.printf("x is float64")
case func(int) float64:
fmt.printf("x is func(int)")
case bool, string:
fmt.printf("x is bool or string")
default:
fmt.printf("don't know the type")
}
}
上述代码编译执行结果如下
type of x :
使用 fallthrough 会强制执行后面的 case 语句,fallthrough 不会判断下一条 case 的表达式结果是否为 true。
package main
import "fmt"
func main() {
switch {
case false:
fmt.println("1、case 条件语句为 false")
fallthrough
case true:
fmt.println("2、case 条件语句为 true")
fallthrough
case false:
fmt.println("3、case 条件语句为 false")
fallthrough
case true:
fmt.println("4、case 条件语句为 true")
case false:
fmt.println("5、case 条件语句为 false")
fallthrough
default:
fmt.println("6、默认 case")
}
}
以上代码执行结果为:
2、case 条件语句为 true
3、case 条件语句为 false
4、case 条件语句为 true
从以上代码输出的结果可以看出:switch 从第一个判断表达式为 true 的 case 开始执行,如果 case 带有 fallthrough,程序会继续执行下一条 case,且它不会去判断下一个 case 的表达式是否为 true。