ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### switch Go 编程语言中 switch 语句的语法如下: ~~~ switch var1 { case val1: ... case val2: ... default: ... } ~~~ 示例: ~~~ 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("优秀!\n" ) case grade == "B", grade == "C" : fmt.Printf("良好\n" ) case grade == "D" : fmt.Printf("及格\n" ) case grade == "F": fmt.Printf("不及格\n" ) default: fmt.Printf("差\n" ) } fmt.Printf("你的等级是 %s\n", grade ) } ~~~ **无表达式的 switch** ~~~ switch { // 表达式被省略了 case num >= 0 && num <= 50: fmt.Println("num is greater than 0 and less than 50") case num >= 51 && num <= 100: fmt.Println("num is greater than 51 and less than 100") case num >= 101: fmt.Println("num is greater than 100") } ~~~ **switch 语句** ``` switch letter { case "a", "e", "i", "o", "u": // 一个选项多个表达式 fmt.Println("vowel") default: fmt.Println("not a vowel") } ``` **Fallthrough 语句** 使用`fallthrough`语句可以在已经执行完成的 case 之后,把控制权转移到下一个 case 的执行代码中 ~~~ package main import ( "fmt" ) func number() int { num := 15 * 5 return num } func main() { switch num := number(); { // num is not a constant case num < 50: fmt.Printf("%d is lesser than 50\n", num) fallthrough case num < 100: fmt.Printf("%d is lesser than 100\n", num) fallthrough case num < 200: fmt.Printf("%d is lesser than 200", num) } } ~~~ ### Type Switch Type Switch 语法格式如下: ~~~ switch x.(type){ case type: statement(s) case type: statement(s) /* 你可以定义任意个数的case */ default: /* 可选 */ statement(s) } ~~~ 示例: ~~~ func main() { var x interface{} //写法一: switch i := x.(type) { // 带初始化语句 case nil: fmt.Printf(" x 的类型 :%T\r\n", i) case int: fmt.Printf("x 是 int 型") case float64: fmt.Printf("x 是 float64 型") case func(int) float64: fmt.Printf("x 是 func(int) 型") case bool, string: fmt.Printf("x 是 bool 或 string 型") default: fmt.Printf("未知型") } //写法二 var j = 0 switch j { case 0: case 1: fmt.Println("1") case 2: fmt.Println("2") default: fmt.Println("def") } //写法三 var k = 0 switch k { case 0: println("fallthrough") fallthrough /* Go的switch非常灵活,表达式不必是常量或整数,执行的过程从上至下,直到找到匹配项; 而如果switch没有表达式,它会匹配true。 Go里面switch默认相当于每个case最后带有break, 匹配成功后不会自动向下执行其他case,而是跳出整个switch, 但是可以使用fallthrough强制执行后面的case代码。 */ case 1: fmt.Println("1") case 2: fmt.Println("2") default: fmt.Println("def") } //写法三 var m = 0 switch m { case 0, 1: fmt.Println("1") case 2: fmt.Println("2") default: fmt.Println("def") } //写法四 var n = 0 switch { //省略条件表达式,可当 if...else if...else case n > 0 && n < 10: fmt.Println("i > 0 and i < 10") case n > 10 && n < 20: fmt.Println("i > 10 and i < 20") default: fmt.Println("def") } } ~~~