我對 Go 中 json null 值的處理感到困惑??梢哉f我有以下示例:package mainimport ( "fmt" "encoding/json" "log")type Fruit struct { Name string Price int Owner string }func main() {jsonData := []byte(`{ "Name": "Standard", "Price" : null, "Owner": null}`) var f Fruit err := json.Unmarshal(jsonData, &f) if err != nil { log.Println(err) } fmt.Printf("Name is : %s\nPrice is : %d\nOwner is : %s\n", f.Name, f.Price, f.Owner) if f.Owner == "" { fmt.Printf("Name should be nil?\n") } if f.Price == 0 { fmt.Printf("Price should be nil?\n") }}現在,我的主要問題是:區分 nil 值和默認值的正確方法是什么?例如,在下面的示例中,我無法知道水果的價格是否尚未設定或實際價格為零。你們如何處理這個問題?在其他語言中,字符串和整數都可以為 null,但 Go 中并非如此。
1 回答

繁星coding
TA貢獻1797條經驗 獲得超4個贊
使用指針:
type Fruit struct {
Name *string `json:"Name,omitempty"`
Price *int `json:"Price,omitempty"`
Owner *string `json:"Owner,omitempty"`
}
然后你可以檢查一個字段是否為零,或者它是否有值。
但是,如果您想區分文檔中存在某個字段并設置為 null 的情況和該字段根本不存在的情況,這對您沒有幫助。
- 1 回答
- 0 關注
- 186 瀏覽
添加回答
舉報
0/150
提交
取消