我对 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")
}
}
现在,我的主要问题是:
区分 nil 值和默认值的正确方法是什么?
例如,在下面的示例中,我无法知道水果的价格是否尚未设定或实际价格为零。
你们如何处理这个问题?
在其他语言中,字符串和整数都可以为 null,但 Go 中并非如此。
收到一只叮咚
繁星coding
随时随地看视频慕课网APP
相关分类