switch语句允许根据值列表测试变量的相等性。 每个值被称为一个情况(case
),并且对于每个开关情况(switch case)检查接通的变量。
在Go编程中,switch有两种类型。
- 表达式开关(switch) - 在表达式开关(switch)中,
case
包含与开关(switch)表达式的值进行比较的表达式。 - 类型开关(switch) - 在类型开关(switch)中,
case
包含与特殊注释的开关(switch)表达式的类型进行比较的类型。
表达式开关(switch)
Go编程语言中的表达式switch语句的语法如下:
switch(boolean-expression or integral type){
case boolean-expression or integral type :
statement(s);
case boolean-expression or integral type :
statement(s);
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
以下规则适用于switch
语句:
在
switch
语句中使用的表达式必须具有整数或布尔表达式, 或者是一个具有单个转换函数为整数或布尔值的类类型。如果未传递表达式,则默认值为true
。在
switch
语句中可以有任意数量的case
语句。 每个case
后面都跟要比较的值和冒号。case
的常量表达式必须是与switch
语句的变量是相同的数据类型,并且它必须是常量或文字。- 当被打开的变量等于一个
case
中的值,那么将执行case
之后的语句。在case
语句中可不需要break
语句。 switch
语句可有一个可选的default
,它必须出现在switch
语句的末尾。default
可用于在没有任何case
为真时执行任务。default
之后可不需要break
语句。
流程图
示例
package main
import "fmt"
func main() {
/* local variable definition */
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)
Go编程语言中的类型switch
语句的语法如下:
switch x.(type){
case type:
statement(s);
case type:
statement(s);
/* you can have any number of case statements */
default: /* Optional */
statement(s);
}
以下规则适用于switch
语句:
switch
语句中使用的表达式必须具有接口{}
类型的变量。- 在
switch
中可以有任意数量的case
语句。 每个case
后面都跟要比较的值和冒号。 case
语句的类型必须与switch
语句中的变量具有相同的数据类型,并且必须是有效的数据类型。- 当
switch
中的变量等于一个case
语句中的值,那么case
之后的语句将被执行。在case
语句中可不需要break
。 switch
语句可以具有可选的default
,它必须出现在switch
语句的末尾。default
情况可用于在没有任何case
语句为真时执行任务。在default
不需要break
语句。
示例
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 :<nil>