假设下面的 answers
是从 JSON 字符串解码的 map[string]interface{}
。
if baths, ok := answers["bathrooms"]; ok {
bathsFloat := baths.(float64)
}
不知何故,我对 接口(interface)转换感到 panic :interface {} 是 nil,不是 float64
。当存在检查为真时,这怎么可能?
最佳答案
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
空
看这个例子:
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>]
关于json - 即使存在值,Go map 也会返回 nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52634800/