将interface{}转换为int时出错 go-gin

huangapple go评论127阅读模式
英文:

Error converting interface{} to int go-gin

问题

我从*gin.Context接收到一个interface{}类型的值:

c.MustGet("account")

当我尝试将其转换为int类型时:

c.MustGet("account").(int)

我收到一个错误:

interface conversion: interface is float64, not int

这个接口的值是1。为什么我会收到这个错误?我在一个SQL查询中使用这个值。我不能将其转换为float64,因为SQL语句会失败。如何将其转换为int类型?

英文:

I have an interface{} type value received from *gin.Context:

c.MustGet("account")

When I try to convert this into int using :

c.MustGet("account").(int)

I get an error:

interface conversion: interface is float64, not int

The value of this interface is 1. Why am I receiving this error? I am using this value in a sql query. I cannot convert this to float64 as the sql statement fails then. How can I convert this into int?

答案1

得分: 3

错误的原因很明显:存储在interface{}值中的动态值的类型是float64,与int类型不同。

提取一个float64类型的值(使用您之前使用的type assertion),然后使用简单的type conversion进行转换:

f := c.MustGet("account").(float64)
i := int(f)
// i 是 int 类型,您可以使用它

或者可以一行完成:

i := int(c.MustGet("account").(float64))

要验证类型和值:

fmt.Printf("%T %v\n", i, i)

两种情况下的输出结果(在Go Playground上尝试):

int 1
英文:

The error is rather self-explanatory: the dynamic value stored in the interface{} value is of type float64 which is different from the type int.

Extract a value of type float64 (using type assertion as you did), and do the conversion using a simple type conversion:

f := c.MustGet("account").(float64)
i := int(f)
// i is of type int, you may use it so

Or in one line:

i := int(c.MustGet("account").(float64))

To verify the type and value:

fmt.Printf("%T %v\n", i, i)

Output in both cases (try it on the Go Playground):

int 1

huangapple
  • 本文由 发表于 2016年8月25日 18:06:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/39142320.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定