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

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式