![](/img/trans.png)
[英]Go err: cannot use cur (type *user.User) as type string in argument to f.WriteString
[英]Use Go goto label on Err
我想使用 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)
}
所以我可以有一個地方將所有錯誤處理放在一個地方,但似乎無法正常工作
./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”語句不得導致任何變量進入 scope,而這些變量在 goto 點處尚未出現在 scope 中。 例如,這個例子:
goto L // BAD v:= 3 L:
是錯誤的,因為跳轉到 label L 跳過了 v 的創建。
所以你需要重構你的代碼。 如果您想在此處繼續使用goto
(而不是if-else
語句),那么您必須將所有聲明向上移動。
請注意,您可以像這樣拆分它:
var v Type
...
L: ...
v = FunctionThatReturnsType()
在這里goto L
應該沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.