将interface {}转换为int在Golang
发布时间:2020-12-16 18:05:42 所属栏目:大数据 来源:网络整理
导读:我刚刚接触Golang,我试图从JSON中获取值并将其转换为int,但它不工作。不知道如何正确地做。 这里是错误消息: ...cannot convert val (type interface {}) to type int: need type assertion 代码: var f interface{} err = json.Unmarshal([]byte(jsonSt
我刚刚接触Golang,我试图从JSON中获取值并将其转换为int,但它不工作。不知道如何正确地做。
这里是错误消息: ...cannot convert val (type interface {}) to type int: need type assertion 代码: var f interface{} err = json.Unmarshal([]byte(jsonStr),&f) if err != nil { utility.CreateErrorResponse(w,"Error: failed to parse JSON data.") return } m := f.(map[string]interface{}) val,ok := m["area_id"] if !ok { utility.CreateErrorResponse(w,"Error: Area ID is missing from submitted data.") return } fmt.Fprintf(w,"Type = %v",val) // <--- Type = float64 iAreaId := int(val) // <--- Error on this line. testName := "Area_" + iAreaId // not reaching here 任何帮助将不胜感激。
代替
iAreaId := int(val) 你想要一个type assertion: iAreaId := val.(int) iAreaId,ok := val.(int) // Alt. non panicking version 为什么你不能convert一个接口类型的值的原因是引用规范部分中的这些规则:
… …
但 iAreaId := int(val) 不是任何一种情况1.-7。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |