gosliceequality

Check if all items in a slice are equal


I need to create a function that:

returns true if all elements in a slice are equal (they will all be the same type)
returns false if any elements in a slice are different

The only way I can think of doing it is to reverse the slice, and compare the slice and the reversed slice.

Is there a better way to do this thats good syntax and more efficient?


Solution

  • I am not sure what your though process was for reversing the slice was, but that would be unnecessary. The simplest algorithm would be to check to see if all elements after the the first are equal to the first:

    func allSameStrings(a []string) bool {
        for i := 1; i < len(a); i++ {
            if a[i] != a[0] {
                return false
            }
        }
        return true
    }