[英]Golang constant struct key
在PHP中,我們可以執行以下操作:
if ($env == "dev")
define("key", "key")
else
define("key", "secret")
// json ouput
//{ key : "value" } or { secret : "value" }
如何正確地將上述PHP方法轉換為GO?
我在想類似的東西:
if *env == "dev" {
type response struct {
key string
...50 more keys that should also be different depending on env
}
} else {
secret string
...50 more keys...
}
但是我想這不僅是錯誤的,而且還會創建大量重復的代碼...
您可以創建一個包含數據結構公共部分的結構類型,也可以創建嵌入該結構的新類型,並僅添加偏離的新字段。 因此,數據結構的公共部分沒有代碼重復:
type Response struct {
F1 string
F2 int
}
func main() {
for _, env := range []string{"dev", "prod"} {
if env == "dev" {
type Resp struct {
Response
Key string
}
r := Resp{Response{"f1dev", 1}, "value"}
json.NewEncoder(os.Stdout).Encode(r)
} else {
type Resp struct {
Response
Secret string
}
r := Resp{Response{"f1pro", 2}, "value"}
json.NewEncoder(os.Stdout).Encode(r)
}
}
}
輸出(在Go Playground上嘗試):
{"F1":"f1dev","F2":1,"Key":"value"}
{"F1":"f1pro","F2":2,"Secret":"value"}
請注意,如果兩個用例的Response
值相同,則也可以使用相同的Response
值:
comResp := Response{"f1value", 1}
if env == "dev" {
type Resp struct {
Response
Key string
}
r := Resp{comResp, "value"}
json.NewEncoder(os.Stdout).Encode(r)
} else {
type Resp struct {
Response
Secret string
}
r := Resp{comResp, "value"}
json.NewEncoder(os.Stdout).Encode(r)
}
您可以使用匿名結構而不創建局部變量(不一定更具可讀性)來縮短上述代碼:
if env == "dev" {
json.NewEncoder(os.Stdout).Encode(struct {
Response
Key string
}{comResp, "value"})
} else {
json.NewEncoder(os.Stdout).Encode(struct {
Response
Secret string
}{comResp, "value"})
}
使用變量:
var key = "secret"
if env == "dev" {
key = "dev"
}
創建映射以序列化為JSON時,請使用該變量:
m := map[string]interface{}{key: "value"}
p, err := json.Marshal(m)
if err != nil {
// handle error
}
// p contains the json value.
這個問題的答案取決於您的實際用例。 這里有3種方法來實現您的要求:
map[string]interface{}
代替struct
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.