即使存在值,Go map 也会返回 nil 值

问题描述 投票:0回答:1

假设下面的

answers
是从 JSON 字符串中解组的
map[string]interface{}

if baths, ok := answers["bathrooms"]; ok {
  bathsFloat := baths.(float64)
}

不知怎的,我对

interface conversion: interface {} is nil, not float64
感到恐慌。当存在检查为真时,这怎么可能?

json dictionary go null
1个回答
1
投票

ok
仅告诉键是否在映射中,与其关联的值是否为
nil
(或者通常是值类型的零值)是另一回事。

参见这个例子:

answers := map[string]interface{}{
    "isnil":  nil,
    "notnil": 1.15,
}

if v, ok := answers["isnil"]; ok {
    fmt.Printf("Value: %v, type: %T\n", v, v)
}
if v, ok := answers["notnil"]; ok {
    fmt.Printf("Value: %v, type: %T\n", v, v)
}

输出(在Go Playground上尝试一下):

Value: <nil>, type: <nil>
Value: 1.15, type: float64

如果

answers
是 JSON 解组的结果,那么如果源中的值是 JSON
nil
,则与其中的键关联的值将为
null

参见这个例子:

var m map[string]interface{}

err := json.Unmarshal([]byte(`{"isnil":null,"notnil":1.15}`), &m)
if err != nil {
    panic(err)
}
fmt.Println(m)

输出(在Go Playground上尝试一下):

map[notnil:1.15 isnil:<nil>]
© www.soinside.com 2019 - 2024. All rights reserved.