The go language goto statement jumps to the specified label implementation method

  • 2020-10-31 21:46:47
  • OfStack

The goto statement performs an unconditional jump between codes through tags. The goto statement can be helpful in quickly breaking out of the loop and avoiding repeated exits. The use of goto statements in the Go language can simplify the implementation of some code.

Use goto to handle errors centrally


package main
import "fmt"
func main() {
 for x := 0; x < 10; x++ {
  for y := 0; y < 10; y++ {
   if y == 2 {
    //  Jump to label 
    goto breakHere
   }
  }
 }
 //  Manual return ,  Avoid executing entry tags 
 return
 //  The label 
breakHere:
 fmt.Println("done")
}

The code description is as follows:

On line 8, use the goto statement to jump to the specified label, which is defined on line 23. At line 13, the tag can only be used by goto, but does not affect the code execution flow. If it is not returned manually here, line 16 will be executed if a condition is not met. Line 15, define the breakHere tag.

With the goto statement, you can quickly exit all loops without additional variables.

Unified error handling

It can be tricky to have multiple error handling with code duplication, such as:


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

The code description is as follows:

At lines 3 and 9, jump the error tag onExit when an error occurs. Lines 17 and 18 summarize all processes for error printing and exit.

Related articles: