【发布时间】:2019-11-01 14:39:04
【问题描述】:
我对 Go 中 json null 值的处理感到困惑。 假设我有以下示例:
package main
import (
"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")
}
}
现在,我的主要问题是:
区分零值和默认值的正确方法是什么?
例如,在下面的示例中,我无法知道水果的价格是没有设置还是实际价格为零。
你们是怎么处理这个问题的?
在其他语言中,字符串和整数都可以为空,但在 Go 中不是这样。
【问题讨论】:
-
使用指针类型,例如
*int/*string.