3 回答

TA貢獻1863條經驗 獲得超2個贊
您可以創建一個結構類型來保存數據結構的公共部分,并且您可以創建嵌入它的新類型,并且只添加有偏差的新字段。所以數據結構的公共部分沒有代碼重復:
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如果兩個用例的值相同,您也可以使用相同的值:
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"})
}

TA貢獻1818條經驗 獲得超8個贊
使用變量:
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.

TA貢獻1820條經驗 獲得超3個贊
這個問題的答案取決于您的實際用例。以下是實現您所要求的 3 種方法:
使用
map[string]interface{}
而不是結構使用不同的結構類型(如問題中的示例)
使用包含“dev”和“prod”環境字段的單一結構類型,使用“json:,omitempty”并在編組為 JSON 之前僅填充必要的字段。
- 3 回答
- 0 關注
- 162 瀏覽
添加回答
舉報