简体   繁体   English

在 Err 上使用 Go 转到 label

[英]Use Go goto label on Err

I want to use label to minimize err part like this:我想使用 label 来最小化这样的错误部分:

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

so i could have one place to put all the err handling in one place, but seems not working as所以我可以有一个地方将所有错误处理放在一个地方,但似乎无法正常工作

./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)

is there a way to use goto to make it work?有没有办法使用 goto 让它工作?

The reason why the compiler is complaining is defined in the Go spec :编译器抱怨的原因在Go 规范中定义:

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.执行“goto”语句不得导致任何变量进入 scope,而这些变量在 goto 点处尚未出现在 scope 中。 For instance, this example:例如,这个例子:

 goto L // BAD v:= 3 L:

is erroneous because the jump to label L skips the creation of v.是错误的,因为跳转到 label L 跳过了 v 的创建。

So you'll need to restructure your code.所以你需要重构你的代码。 If you want to keep using goto here (as opposed to, say, if-else statements), then you'll have to move all the declarations up.如果您想在此处继续使用goto (而不是if-else语句),那么您必须将所有声明向上移动。

Note that you can split it like this:请注意,您可以像这样拆分它:

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

It should be OK to goto L here.在这里goto L应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM