加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

将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一个接口类型的值的原因是引用规范部分中的这些规则:

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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读