switch 语句允许针对值列表对变量进行相等性测试。
switch - 语法
Go编程语言中 expression switch 语句的语法如下-
switch(boolean-expression or integral type){ case boolean-expression or integral type : statement(s); case boolean-expression or integral type : statement(s); /* 你可以有任意数量的case语句 */ default : /* 可选 */ statement(s); }
switch - 流程图
switch - 示例
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
Type Switch - 语法
Go编程中 type switch 语句的语法如下-
switch x.(type){ case type: statement(s); case type: statement(s); /* 可多个case选项 */ default: /* 可选 */ statement(s); }
Type 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>
参考链接
https://www.learnfk.com/go/go-switch-statement.html
标签:case,grade,fmt,无涯,switch,Printf,Go,type From: https://blog.51cto.com/u_14033984/8911068