英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论