I have a function which checks if array lengths are the same:
func checkArrayLengthsMatch(desiredLength int, arrays ...[]any) bool {
for _, array := range arrays {
if len(array) != desiredLength {
return false
}
}
return true
}
But this doesn't work because of the []any
.
array1 := []string{"1", "2"}
array2 := []int{1, 2}
checkArrayLengthsMatch(2, array1, array2)
gives the error cannot use array1 (variable of type []string) as type []any in argument to checkArrayLengthsMatch
Is there any way to achieve this functionality without having to write a long if statement? (e.g. if len(array1) != 2 || len(array2) != 2
) Generics?
I want to be able to support checking arrays of various types.
Go playground link: https://go.dev/play/p/yKisBIOZktI
CodePudding user response:
If you need to pass different types of arrays to the same function, generics won't work, but reflection will:
func checkArrayLengthsMatch(desiredLength int, arrays ...any) bool {
for _, array := range arrays {
if reflect.ValueOf(array).Len() != desiredLength {
return false
}
}
return true
}
This will also work for maps, channels, and strings.