我有一个从*gin.Context收到的interface{}类型值
c.MustGet("account")当我尝试使用以下命令将其转换为int时:
c.MustGet("account").(int)我得到一个错误:
interface conversion: interface is float64, not int此接口的值为1。为什么我会收到这个错误?我在sql查询中使用此值。我不能将它转换为float64,因为sql语句会失败。如何将其转换为int
发布于 2016-08-25 18:13:10
这个错误是不言而喻的:存储在interface{}值中的动态值的类型是float64,这与int的类型不同。
提取float64类型的值(像您一样使用type assertion ),并使用简单的type conversion进行转换
f := c.MustGet("account").(float64)
i := int(f)
// i is of type int, you may use it so或者一行:
i := int(c.MustGet("account").(float64))要验证类型和值,请执行以下操作:
fmt.Printf("%T %v\n", i, i)两种情况下的输出(在Go Playground上试用):
int 1https://stackoverflow.com/questions/39142320
复制相似问题