douju4594 2013-08-04 09:00 采纳率: 100%
浏览 677
已采纳

将interface {}转换为int

I'm trying to get a value from a JSON and cast it to int but it doesn't work, and I 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
  • 写回答

9条回答 默认 最新

  • dpdx51205 2013-08-04 09:32
    关注

    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) 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.

    But

    iAreaId := int(val)
    

    is not any of the cases 1.-7.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案