我是Golang的新手,我试图从JSON中获取一个值并将其转换为int,但不起作用。不知道如何正确地做到这一点。
以下是错误消息:
...无法将val(type interface {})转换为int类型:need type assertion和代码: var f interface {} err = json.Unmarshal([] byte jsonStr)& f) if err!= nil { utility.CreateErrorResponse(w,Error:未能解析JSON数据。) 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)//< ---这条线上的错误。 testName:=Area_+ iAreaId // not reach here
赞赏。
解决方案而不是
iAreaId:= int(val)你需要一个类型断言:
iAreaId:= val。(int ) iAreaId,ok:= val。(int)// Alt。非恐慌版本你不能 convert 界面类型值是引用规范部分中的这些规则:
转换是表达式的形式 T(x)其中 T 是一个类型, x ...
在任何这些情况下,非常量值x都可以转换为T类型:
但是
iAreaId:= int(val)是不是任何情况1.-7。
I'm new to Golang and I'm trying to get a value from a JSON and cast it to int but it doesn't work. Don't know how to do it properly.
Here is the error message:
...cannot convert val (type interface {}) to type int: need type assertionAnd the Code:
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 hereany help would be appreciated.
解决方案Instead of
iAreaId := int(val)you want a type assertion:
iAreaId := val.(int) iAreaId, ok := val.(int) // Alt. non panicking versionThe reason why you cannot convert an interface typed value are these rules in the referenced specs parts:
Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.
...
A non-constant value x can be converted to type T in any of these cases:
But
iAreaId := int(val)is not any of the cases 1.-7.
更多推荐
将接口{}转换为Golang中的int
发布评论