假设下面的answers
是从JSON字符串中解组的map[string]interface{}
。
if baths, ok := answers["bathrooms"]; ok {
bathsFloat := baths.(float64)
}
某种程度上,我对interface conversion: interface {} is nil, not float64
感到恐慌。存在检查为真时怎么办?
答案 0 :(得分:0)
ok
仅告诉键是否在映射中,与键相关联的值是nil
(或通常他值类型的零值)还是另一回事。 / p>
请参见以下示例:
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>]