【问题标题】:Use Go goto label on Err在 Err 上使用 Go goto 标签
【发布时间】:2021-02-17 14:14:19
【问题描述】:

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

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 让它工作?

【问题讨论】:

  • 不,错误解释了原因。预先声明所有内容,使用条件块或可以提前返回的函数
  • @JimB 好的,谢谢。

标签: go label goto


【解决方案1】:

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

执行“goto”语句一定不能导致任何变量到来 进入在 goto 点尚未在范围内的范围内。 比如这个例子:

  goto L  // BAD  
  v := 3
L:

是错误的,因为跳转到标签 L 跳过了 v 的创建。

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

注意,你可以这样拆分:

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

这里goto L应该没问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2011-02-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多