我試圖理解為什么兩個函數(shù)返回相同的輸出。據(jù)我了解,省略 empty 的目的是不將該鍵添加到結(jié)果結(jié)構(gòu)中。我寫了這個例子,我希望第一個輸出沒有“空”鍵,但由于某種原因,它的值仍然顯示為 0。package mainimport ( "encoding/json" "fmt" "strings")type agentOmitEmpty struct { Alias string `json:"Alias,omitempty"` Skilled bool `json:"Skilled,omitempty"` FinID int32 `json:"FinId,omitempty"` Empty int `json:"Empty,omitempty"`}type agent struct { Alias string `json:"Alias"` Skilled bool `json:"Skilled"` FinID int32 `json:"FinId"` Empty int `json:"Empty"`}func main() { jsonString := `{ "Alias":"Robert", "Skilled":true, "FinId":12345 }` fmt.Printf("output with omit emtpy: %v\n", withEmpty(strings.NewReader(jsonString))) // output with omit emtpy: {Robert true 12345 0} fmt.Printf("output regular: %v\n", withoutEmpty(strings.NewReader(jsonString))) // output without omit: {Robert true 12345 0}}func withEmpty(r *strings.Reader) agentOmitEmpty { dec := json.NewDecoder(r) body := agentOmitEmpty{} err := dec.Decode(&body) if err != nil { panic(err) } return body}func withoutEmpty(r *strings.Reader) agent { dec := json.NewDecoder(r) body := agent{} err := dec.Decode(&body) if err != nil { panic(err) } return body}
- 1 回答
- 0 關(guān)注
- 122 瀏覽
添加回答
舉報
0/150
提交
取消