Golang 使用switch和多值case
在Golang中,switch语句是一个非常有用的控制语句。除了if语句,switch语句也被广泛应用于逻辑控制的场景。而多值case也是switch语句的一种常见形式,可以匹配多个值执行同一个代码块。
switch语句的基本使用
switch语句的语法很简单,只需在switch后面的括号中放置要判断的值,然后在大括号中编写相应的逻辑分支即可。下面是一个简单的例子:
package main
import "fmt"
func main() {
var x int = 2
switch x {
case 1:
fmt.Println("x is equal to 1")
case 2:
fmt.Println("x is equal to 2")
case 3, 4, 5:
fmt.Println("x is equal to 3, 4, or 5")
default:
fmt.Println("x is not equal to any of the above")
}
}
在上面的例子中,switch语句会先判断x的值,然后根据不同的情况执行不同的代码块。
在匹配case时,还可以用多个值一起匹配。例如,上面的代码中,case 3, 4, 5就是一种多值case的形式,表示当x的值为3、4、5中的任意一个时,会执行相应的代码块。
多值case的使用
除了上面提到的使用多个值在同一个case中匹配,还可以在不同的case中匹配相同的多个值。例如:
package main
import "fmt"
func main() {
var x int = 3
switch x {
case 1, 2:
fmt.Println("x is equal to 1 or 2")
case 3, 4:
fmt.Println("x is equal to 3 or 4")
default:
fmt.Println("x is not equal to any of the above")
}
}
在上面的代码中,多值case有两种形式,分别是1,2和3,4。当x的值分别为1、2、3、4中的任意一个时,会执行相应的代码块。
值得注意的是,当使用多值case时,只有所有的选项都不匹配时我们才会进入到default中。
另外,我们还可以在case中使用表达式,而不仅仅是值。例如:
package main
import "fmt"
func main() {
var x int = 10
switch {
case x > 0 && x < 5:
fmt.Println("x is between 0 and 5")
case x >= 5 && x < 10:
fmt.Println("x is between 5 and 10")
case x == 10:
fmt.Println("x is 10")
default:
fmt.Println("x is not in any of the above ranges")
}
}
在上面的代码中,我们没有在switch后面声明要判断的值,而是直接在case中使用了表达式。每一个case中的表达式都可以根据需要进行更改。
结论
在Golang中,switch语句是一个非常强大的控制语句。多值case是switch语句的一种常见形式,可以匹配多个值执行同一个代码块。通过上面的例子,你已经掌握了switch语句和多值case的基本用法,希望这篇文章对你有所帮助。
极客笔记