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
?
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
", i, i)
Output in both cases (try it on the Go Playground):
int 1