在 Go 语言 中,实现 循环 的跳转除了使用 break 和 continue 以外,还可以使用 goto 语句。当然,goto语句不仅可以使用在循环中,还可以使用在代码的任何地方。
goto 语句使用最多的场景就是程序的错误处理,也就是当程序出错时,统一跳转到相应的标签处,统一处理错误。
...
goto lable
...
label:
//do something
使用 goto 后面加上 label 名,可以直接将代码跳转到 label 的地方执行。
使用 goto 语句,跳出循环
package main
import "fmt"
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用goto语句,跳出循环
for i := 0; i < 5; i++ {
for j := 0; j < 4; j++ {
if j == 2{
goto over
}
}
}
over:
fmt.Println("Over")
}
程序运行后,控制台输出如下:
我们定义了双重 for循环,并在内层循环中使用 if 语句 判断,如果 j 的值为 2,那么就使用 goto 语句,直接跳转到标签 over 的地方执行。
我们看到,程序只输出了 i 为 0 和 j 为 1 的情况,因为当 j 为 2 时,goto 语句直接将代码跳转到了 over 标签的位置,所以所有的循环都不会继续往下执行。
使用 goto 语句,处理错误
package main
import "fmt"
func checkUserParam(val int)bool{
if val <= 0{
return false
}
return true
}
func checkPageSize(pageSize int)bool{
if pageSize > 100{
return false
}
return true
}
func main() {
fmt.Println("嗨客网(www.haicoder.net)")
//使用goto语句,处理错误
if checkUserParam(10) == false{
fmt.Println("User Param check Err")
goto err
}
fmt.Println("User Param check OK")
if checkPageSize(200) == false{
fmt.Println("PageSize check Err")
goto err
}
fmt.Println("PageSize check OK")
err:
fmt.Println("Over")
}
程序运行后,控制台输出如下:
我们定义了两个 函数,一个用于校验用户输入参数,一个用于校验 pageSize,如果参数不合法,则输出 False。
在主函数里面,我们调用这两个函数,如果出错,都跳转到统一的错误处理的 label。
Go 语言的 goto 语句可以实现程序的跳转,goto 语句使用最多的场景就是程序的错误处理,也就是当程序出错时,统一跳转到相应的标签处,统一处理错误。