Contents
3.3. 分支选择-switch¶
分支选择可以理解为一种批量的if语句,使用switch语句可方便地对大量的值进行判断。 在Go语言中的switch,不仅可以基于常量进行判断,还可以基于表达式进行判断。
3.3.1. 1.基本写法¶
package main
import "fmt"
func main() {
var name = "hello"
switch name {
case "hello":
fmt.Println(1)
case "help":
fmt.Println(2)
case "hapend":
fmt.Println(3)
default:
fmt.Println(0)
}
}
package main
import "fmt"
func main() {
year := 2020
month := 6
days := 18
switch month {
case 1, 3, 5, 7, 8, 10, 12:
days = 31
case 4, 6, 9, 11:
days = 30
case 2:
if (year%4 == 0 && year%100 != 0) || year%400 == 0 {
days = 29
} else {
days = 28
}
default:
days = -1
}
fmt.Printf("%d年 %d月的天数为%d天 \n", year, month, days)
}
1.1 一分支多值¶
package main
import "fmt"
func main() {
var a = "mum"
switch a {
case "mum","daddy": // 不同case表达式使用,分隔
fmt.Println("family")
}
}
1.2 分支表达式¶
package main
import "fmt"
func main() {
var r int = 11
switch { // 这种情况下switch后面不再跟判断变量,连判断目标都没有了。
case r > 10 && r < 20:
fmt.Println(r) //11
}
}
1.3 跨越case的fallthrough-兼容C语言的case设计¶
package main
import "fmt"
func main() {
var name = "hello"
switch {
case name == "hello":
fmt.Println("hello")
fallthrough //fallthrough 关键字,执行完一个case继续执行下面的case
case name != "world":
fmt.Println("world")
}
}
//hello
//world
3.3.2. 2.跳转至指定的代码标签(goto)¶
goto 语句通过标签进行代码间的无条件跳转,goto语句可以在快速跳出循环、避免重复退出上有一定的帮助。 Go语言中使用goto语句能简化一些代码的实现过程。
如果要退出2层循环,传统的办法如下:
package main
func main() {
var breakAgain bool
// 外循环
for x := 0; x < 10; x++ {
// 内循环
for y := 0; y < 10; y++ {
if y == 2{
//设置退出标记
breakAgain = true
break
}
}
if breakAgain{
break
}
}
}
2.1 使用goto集中处理错误¶
package main
import "fmt"
func main() {
// 外循环
for x := 0; x < 10; x++ {
// 内循环
for y := 0; y < 10; y++ {
if y == 2{
goto breakHere // 跳转到标签
}
}
}
return
// 标签
breakHere:
fmt.Println("done")
}
2.2 goto统一错误处理¶
package main
import "fmt"
func main() {
err :=firstCheckError()
if err != nil {
goto onExit // 发生错误时,跳转错误标签onExit
}
err = secondCheckError()
if err != nil {
goto onExit
}
fmt.Println("done")
return
// 汇总所有的流程进行错误打印并退出进程
onExit:
fmt.Println("error")
exitPrcess()
}