我對 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") }}現(xiàn)在,我的主要問題是:區(qū)分 nil 值和默認(rèn)值的正確方法是什么?例如,在下面的示例中,我無法知道水果的價格是否尚未設(shè)定或?qū)嶋H價格為零。你們?nèi)绾翁幚磉@個問題?在其他語言中,字符串和整數(shù)都可以為 null,但 Go 中并非如此。
1 回答

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