我想使用标签来最小化错误部分,如下所示:package mainimport ( "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来使它工作?
1 回答

Smart猫小萌
TA贡献1911条经验 获得超7个赞
编译器抱怨的原因在 Go 规范中定义:
执行 “goto” 语句不得导致任何变量进入在 goto 点时尚未在作用域内的范围。例如,此示例:
goto L // BAD
v := 3
L:
是错误的,因为跳转到标签 L 会跳过 v 的创建。
因此,您需要重构代码。如果你想继续在这里使用(而不是,比如说,语句),那么你必须把所有声明都向上移动。gotoif-else
请注意,您可以像这样拆分它:
var v Type
...
L: ...
v = FunctionThatReturnsType()
在这里应该没问题。goto L
- 1 回答
- 0 关注
- 125 浏览
添加回答
举报
0/150
提交
取消