Golang type assertion (any)

  Kiến thức lập trình

This seems likely to be a duplicate but I couldn’t find a solution. Please point me in the right direction if it is a duplicate

I am relatively new to Go and here I am trying to create a helper function to be able to compare two arrays.

Here’s my code:

func compareArrays(array0 []any, array1 []any) (ok bool, index int) {

    if len(array0) != len(array1) {
        return false, -1
    }

    for index, value := range array0 {
        if value != array1[index] {
            return false, index
        }
    }

    return true, 0
}

The code should just compare each element of the first array to the second array and return the index of the first error it finds.

I have intentionally set the array types as []any in order to be able to pass in any type of array.

However, when I try to pass in two arrays of type []float64, I get this message:

Cannot use ‘floatArray’ (type []float64) as the type []any

What am I doing wrong here and how can I achieve a generalized comparison function to compare two arrays if this is not possible?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT