John Difool
John Difool

Reputation: 5732

Casting interface can reflecting on array types

The code below is an adaption of a Python script. Of course, it doesn't compile and there are a couple of reasons for this.

I am struggling to understand how it's possible to fix it so it gives the right result.

In particular:

  1. I want to represent either a type (float64) or an array of this type so I am naively using an []interface but then passing an array won't work. I understand I could deep copy an interface array with my array but is it the only way?

  2. The reflection check works (kinda) but then I am back to casting an interface to an []interface and that doesn't work.

  3. A simpler way would be to pass []float but I also want to make the code generic (oops! ;-) enough to accept [][]floats and recursively descend with the comparisons.

Am I completely offtrack?

func assertArrayEquals(first []interface{}, second []interface{}) bool {
    if len(first) != len(second) {
        return false
    }
    for i := range first {
        if reflect.ValueOf(first[i]).Kind() == reflect.Array {
            assertArrayEquals([]interface{}(first[i]), []interface{}(second[i]))
        } else if second[i] != first[i] {
            return false
        }
    }
    return true
}

func main() {
    assertArrayEquals([]float64{[]float64{0, 1}, []float64{0, 1}}, []float64{[]float64{0, 1}, []float64{0, 1}})
}

Upvotes: 0

Views: 28

Answers (1)

Thundercat
Thundercat

Reputation: 121139

Here's one way to implement assertArrayEquals:

func assertArrayEquals(first interface{}, second interface{}) bool {
    return reflect.DeepEqual(first, second)
}

playground example

Upvotes: 1

Related Questions