switch语句允许根据值列表测试变量的相等性。 每个值被称为一个情况(case),并且对于每个开关情况(switch case)检查接通的变量。
在Go编程中,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后面都跟要比较的值和冒号。
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
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语句:
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>