Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if all array lengths match in Go

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading