1 回答
TA贡献1963条经验 获得超6个赞
如果您查看 Unmarshal 的文档。你会发现 Unmarshal 中已知的 Numbers 类型是float64
为了将 JSON 解组为接口值,Unmarshal 将其中一项存储在接口值中:
bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null
因此,当您尝试 Unmarshal an int 您将得到它作为 float 64。应该先键入 assert 它float64 intf.(float64)然后将其转换为int
例如 :
intf, ok := js["cols"]
if !ok {
return fmt.Errorf("tag 'cols' missing in JSON data")
}
var cols, rows int
ucols, ok := intf.(float64)
if !ok {
return fmt.Errorf("tag 'cols' cannot be converted to float64")
}
cols = int(ucols)
- 1 回答
- 0 关注
- 313 浏览
添加回答
举报
