我刚刚接触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一个接口类型的值的原因是引用规范部分中的这些规则:
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.
但
iAreaId := int(val)
不是任何一种情况1.-7。