将interface {}转换为int [英] Convert interface{} to int

查看:576
本文介绍了将interface {}转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从JSON中获取一个值并将其转换为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.

这是错误消息:

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

您需要类型声明:

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:

转换是形式为T(x)的表达式,其中T是类型,而x是可以转换为类型T的表达式.

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.

...

在以下任何一种情况下,非恒定值x都可以转换为T型:

A non-constant value x can be converted to type T in any of these cases:

  1. x可分配给T.
  2. x的类型和T具有相同的基础类型.
  3. x的类型和T是未命名的指针类型,并且它们的指针基类型具有相同的基础类型.
  4. x的类型和T都是整数或浮点类型.
  5. x的类型和T都是复数类型.
  6. x是整数或字节或runes的切片,T是字符串类型.
  7. x是一个字符串,T是一个字节或符文切片.

但是

iAreaId := int(val)

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

is not any of the cases 1.-7.

这篇关于将interface {}转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆