在 Err 上使用 Go goto 标签

Use Go goto label on Err

我想像这样使用标签来最小化错误部分:

package main
import (
    "fmt"
    consul "github.com/hashicorp/consul/api"
    "os"
)
func main(){
    client,err := consul.NewClient(consul.DefaultConfig())
    if err != nil {
        goto Err
    }
    agent := client.Agent()
    checkReg := agent.AgentCheckRegistration{
        ID:   "test-check",
        Name: "test-check",
        Notes: "some test check",
    }
    if err = agent.CheckRegister(checkReg); err !=nil{
        goto Err
    }
Err:
    fmt.Println(err)
    os.Exit(2)
}

所以我可以有一个地方将所有错误处理放在一个地方,但似乎无法正常工作

./agent.CheckRegister.go:10:8: goto Err jumps over declaration of checkReg at 
./agent.CheckRegister.go:13:19: agent.AgentCheckRegistration undefined (type *api.Agent has no field or method AgentCheckRegistration)

有没有办法使用 goto 使其工作?

编译器报错的原因定义在 Go spec:

Executing the "goto" statement must not cause any variables to come into scope that were not already in scope at the point of the goto. For instance, this example:

  goto L  // BAD  
  v := 3
L:

is erroneous because the jump to label L skips the creation of v.

所以您需要重构您的代码。如果您想在此处继续使用 goto(而不是 if-else 语句),那么您必须将所有声明向上移动。

请注意,您可以这样拆分它:

   var v Type
   ...
L: ...
   v = FunctionThatReturnsType()

这里goto L应该可以吧