我想使用标签来最小化这样的错误部分:
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规范中定义了编译器抱怨的原因:
执行“ goto”语句一定不能使任何变量在goto时尚未进入作用域。例如,此示例:
goto L // BAD v := 3 L:
是错误的,因为跳转到标签L会跳过v的创建。
因此,您需要重组代码。如果要继续使用goto
此处(而不是if-else
声明),则必须将所有声明上移。
请注意,您可以像这样拆分它:
var v Type
...
L: ...
v = FunctionThatReturnsType()
到goto L
这里应该可以。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句