HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

Convert interface{} to int

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
convertinterfaceint

Problem

I'm trying to get a value from a JSON and cast it to int but it doesn't work, and I don't know how to do it properly.

Here is the error message:

...cannot convert val (type interface {}) to type int: need type assertion


And the code:

var f interface{}
    err = json.Unmarshal([]byte(jsonStr), &f)
    if err != nil {
        utility.CreateErrorResponse(w, "Error: failed to parse JSON data.")
        return
    }

    m := f.(map[string]interface{})

    val, ok := m["area_id"]
    if !ok {
        utility.CreateErrorResponse(w, "Error: Area ID is missing from submitted data.")
        return
    }

    fmt.Fprintf(w, "Type = %v", val)   // <--- Type = float64
    iAreaId := int(val)                // <--- Error on this line.
    testName := "Area_" + iAreaId      // not reaching here

Solution

Instead of

iAreaId := int(val)


you want a type assertion:

iAreaId := val.(int)
iAreaId, ok := val.(int) // Alt. non panicking version


The reason why you cannot convert an interface typed value are these rules in the referenced specs parts:

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

...

A non-constant value x can be converted to type T in any of these cases:

  • x is assignable to T.



  • x's type and T have identical underlying types.



  • x's type and T are unnamed pointer types and their pointer base types have identical underlying types.



  • x's type and T are both integer or floating point types.



  • x's type and T are both complex types.



  • x is an integer or a slice of bytes or runes and T is a string type.



  • x is a string and T is a slice of bytes or runes.



But

iAreaId := int(val)


is not any of the cases 1.-7.

Code Snippets

iAreaId := int(val)
iAreaId := val.(int)
iAreaId, ok := val.(int) // Alt. non panicking version
iAreaId := int(val)

Context

Stack Overflow Q#18041334, score: 288

Revisions (0)

No revisions yet.