golang swith case

发布时间:2024-10-01 13:33:27

Go语言中的Switch Case语句

在Go语言中,switch case语句用于根据不同的条件执行不同的代码块。它是一种更为简洁和优雅的方式来处理多个条件分支,相比于传统的if-else语句。

基本语法

switch case语句的基本语法如下:

switch expression { case value1: // 执行语句块1 case value2: // 执行语句块2 ... default: // 如果没有匹配的值则执行default语句块 }

其中,expression可以是一个变量或函数表达式,value1、value2等为待匹配的值。

匹配字符串

在Go语言中,我们可以使用switch case语句来匹配字符串。例如:

func processString(s string) { switch s { case "apple": fmt.Println("这是一个苹果") case "banana": fmt.Println("这是一个香蕉") default: fmt.Println("未知的水果") } }

上述代码中,我们可以根据传入的字符串参数s的值,来执行相应的代码块。

匹配多个值

使用逗号(,)分隔多个值,可以同时匹配多个值执行相同的代码块。例如:

func processNumber(num int) { switch num { case 1, 3, 5: fmt.Println("奇数") case 2, 4, 6: fmt.Println("偶数") default: fmt.Println("其他数字") } }

上述代码中,如果num的值为1、3或5,则输出"奇数";如果num的值为2、4或6,则输出"偶数";否则输出"其他数字"。

使用表达式

在Go语言中,我们还可以在case语句中使用表达式。例如:

func processGrade(score int) { switch { case score >= 90: fmt.Println("优秀") case score >= 80: fmt.Println("良好") case score >= 60: fmt.Println("及格") default: fmt.Println("不及格") } }

上述代码中,我们根据score的值来输出对应的等级。

使用Fallthrough

在Go语言中,switch case语句默认是不会自动向下执行的,但通过使用fallthrough关键字可以实现。例如:

func processOption(option string) { switch option { case "A": fmt.Println("选择了A") fallthrough case "B": fmt.Println("选择了B") case "C": fmt.Println("选择了C") default: fmt.Println("无效选项") } }

上述代码中,如果option的值为"A",则会输出"选择了A"和"选择了B";如果option的值为"B",则会输出"选择了B";如果option的值为"C",则会输出"选择了C";否则输出"无效选项"。

总结

switch case是Go语言中用于处理多个条件分支的一种语句,它比传统的if-else语句更为简洁和优雅。我们可以使用它来匹配字符串、多个值或表达式,并且还可以使用fallthrough关键字实现向下执行。通过灵活运用switch case语句,我们能够更加清晰地处理各种条件分支,使代码更加易读和可维护。

相关推荐