4

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?

icza
  • 389,944
  • 63
  • 907
  • 827
codec
  • 7,978
  • 26
  • 71
  • 127

1 Answers1

3

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
icza
  • 389,944
  • 63
  • 907
  • 827