Search code examples
gotype-assertion

Golang Type Assertion Arrays


For what I understand type assertion can only be used in interfaces and basically check if a determined type implements the interface.

I am having some weird scenarios:

func binder(value interface{}) {
   // Does not work
   valueInt, ok := value.(int)

   // Works
   valueInt, ok := value.(float64)

   // Does not work 
   coordinates, ok := value.([]int)

   // Does not work 
   coordinates, ok := value.([]float64) 
}

Basically, my value is an empty interface and I am getting from a json.Unmarshall.

Scenario 1

when I pass a simple integer it does not work but if I check if is a float it works...

Scenario 2

When I pass an array of int or floats does not work! As you can see when I am debugging I am receiving an array but for some reason assertion does not work.

enter image description here


Solution

  • Your question is unclear, but it appears to boil down to the following:

    By default, json.Unmarshal unmarshals all numbers into float64, since all numbers in JSON are floats. If you want some other type, you need to use a specific type in your target type. Examples:

    var x map[string]interface{}
    json.Unmarshal([]byte(`{"foo":123}`), &x) // { "foo": float64(123) }
    

    vs:

    var x map[string]int64
    json.Unmarshal([]byte(`{"foo":123}`), &x) // { "foo": int64(123) }
    

    And by default, all JSON arrays unmarshal to []interface{}, because the members can be of any type, including mixed types. If you want a specific type, again, you have to be specific:

    var x interface{}
    json.Unmarshal([]byte(`[1,2,3]`), &x) // []interface{}{float64(1), float64(2), float64(3)}
    

    vs:

    var x []int64
    json.Unmarshal([]byte(`[1,2,3]`), &x) // []int64{1,2,3}