将接口{}转换为Golang中的int [英] convert interface{} to int in Golang
问题描述
我是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类型:
- x可分配给T。
- x的类型和T具有相同的基础类型。
- x的类型和T是未命名的指针类型及其指针基本类型具有相同的基础类型。
- x的类型和T都是整型或浮点型。
- x的类型和T都是复杂类型。
- x是整数或字节或符文片段T是一个字符串类型。
- x是一个字符串,T是一个字节或符文片段。
blockquote>
但是
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 assertion
And 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 here
any help would be appreciated.
解决方案Instead of
iAreaId := int(val)
you want a type assertion:
iAreaId := val.(int) iAreaId, ok := val.(int) // Alt. non panicking version
The 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)
whereT
is a type andx
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:
- x is assignable to T.
- x's type and T have identical underlying types.
- x's type and T are unnamed pointer types and their pointer base types have identical underlying types.
- x's type and T are both integer or floating point types.
- x's type and T are both complex types.
- x is an integer or a slice of bytes or runes and T is a string type.
- x is a string and T is a slice of bytes or runes.
But
iAreaId := int(val)
is not any of the cases 1.-7.
这篇关于将接口{}转换为Golang中的int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!