golang switch case 匹配字符串
在Go语言中,switch
语句是用于处理多个条件的一种流控制语句。通过switch
语句结合case
和fallthrough
关键字,我们可以方便地处理多个条件分支。在本文中,我们将详细讨论如何使用switch
语句来匹配字符串。
switch语句的基本语法
switch
语句基本的语法形式如下:
switch variable {
case value1:
// 当variable等于value1时执行这里的代码
case value2:
// 当variable等于value2时执行这里的代码
...
default:
// 当没有匹配的case时执行这里的代码
}
switch
语句会将variable
和各个case
后面的值进行比较,当variable
等于某个case
后面的值时,就会执行对应的代码块。如果没有匹配的case
,则会执行default
后面的代码块。其中,default
是可选的,如果没有匹配的case
,则会执行default
中的代码块。
接下来,我们将看一些具体的示例来说明如何在Go语言中使用switch
语句匹配字符串。
示例代码
package main
import "fmt"
func main() {
fruit := "apple"
switch fruit {
case "apple":
fmt.Println("It's an apple!")
case "banana":
fmt.Println("It's a banana!")
case "orange":
fmt.Println("It's an orange!")
default:
fmt.Println("It's not a fruit we know.")
}
}
在上面的示例代码中,我们定义了一个fruit
变量,并根据不同的fruit
值执行不同的代码块。当fruit
为”apple”时,会输出”It’s an apple!”;当fruit
为”banana”时,会输出”It’s a banana!”;当fruit
为”orange”时,会输出”It’s an orange!”;其他情况下,会输出”It’s not a fruit we know.”。
运行以上代码,输出为:
It's an apple!
模式匹配
在Go语言中,switch
语句还支持对表达式进行模式匹配。通过case
后面加上一个表达式,可以使case
条件更加灵活。
以下是一个使用字符串模式匹配的示例:
package main
import "fmt"
func main() {
fruit := "apple"
switch {
case fruit == "apple":
fmt.Println("It's an apple!")
case fruit == "banana":
fmt.Println("It's a banana!")
case fruit == "orange":
fmt.Println("It's an orange!")
default:
fmt.Println("It's not a fruit we know.")
}
}
在这个示例中,我们使用switch
后面没有跟具体的变量,而是对fruit
值进行了比较。运行以上代码,输出依然为:
It's an apple!
多个条件匹配
有时候我们可能会希望在一个case
中匹配多个条件,这时候可以使用逗号分隔多个条件,只要有一个条件匹配即可。
下面是一个示例:
package main
import "fmt"
func main() {
fruit := "apple"
switch fruit {
case "apple", "banana":
fmt.Println("It's a common fruit!")
case "orange", "peach":
fmt.Println("It's a juicy fruit!")
default:
fmt.Println("It's not a fruit we know.")
}
}
在这个示例中,当fruit
为”apple”或”banana”时,输出”It’s a common fruit!”;当fruit
为”orange”或”peach”时,输出”It’s a juicy fruit!”。其他情况下,输出”It’s not a fruit we know.”。
fallthrough关键字
在switch
语句中,当某个case
执行完毕后,会自动退出switch
语句。但有时候我们希望在匹配成功后继续执行后面的case
,这时候可以使用fallthrough
关键字。
以下是一个使用fallthrough
的示例:
package main
import "fmt"
func main() {
fruit := "apple"
switch fruit {
case "apple":
fmt.Println("It's an apple!")
fallthrough
case "banana":
fmt.Println("It's a banana!")
case "orange":
fmt.Println("It's an orange!")
default:
fmt.Println("It's not a fruit we know.")
}
}
在这个示例中,当fruit
为”apple”时,会输出”It’s an apple!”,并且由于使用了fallthrough
关键字,继续执行下一个case
,输出”It’s a banana!”。
结语
通过以上示例,我们了解了在Go语言中如何使用switch
语句匹配字符串。通过case
、模式匹配、多条件匹配和fallthrough
关键字,我们可以根据不同的条件执行不同的代码块,从而实现灵活的逻辑控制。