将interface {}转换为int在Golang

前端之家收集整理的这篇文章主要介绍了将interface {}转换为int在Golang前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚接触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) 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:

  1. x is assignable to T.
  2. x’s type and T have identical underlying types.
  3. x’s type and T are unnamed pointer types and their pointer base types have identical underlying types.
  4. x’s type and T are both integer or floating point types.
  5. x’s type and T are both complex types.
  6. x is an integer or a slice of bytes or runes and T is a string type.
  7. x is a string and T is a slice of bytes or runes.

iAreaId := int(val)

不是任何一种情况1.-7。

猜你在找的Go相关文章