Goto usage and usage scenarios in golang (transfer)

Reposted from : goto in golang

Scenario 1: Jumping out of multiple loops

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")
}

Scenario 2: Jump to the end of the program, perform unified error handling, and avoid error handling code blocks being copied multiple times

err := firstCheckError()
    if err != nil {
        goto onExit
    }
 
    err = secondCheckError()
 
    if err != nil {
        goto onExit
    }
 
    fmt.Println("done")
 
    return
 
onExit:
    fmt.Println(err)
    exitProcess()

Reposted from : goto in golang

Guess you like

Origin blog.csdn.net/qq_41767116/article/details/130051400