XXX
XXX

Reputation: 633

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?

Upvotes: 7

Views: 9838

Answers (3)

rodrigocfd
rodrigocfd

Reputation: 8023

With Go generics you have the slices package, which can provide you an one-line solution:

strs := []string{"ab", "ab", "ab", "ab"}
allEqual := !slices.ContainsFunc(strs, func(s string) bool { return s != strs[0] })

Playground here.

Upvotes: 0

Appaji Chintimi
Appaji Chintimi

Reputation: 675

Although there is an accepted answer, I'm just posting it with range keyword.

func allSameStrings(a []string) bool {
    for i, v := range(a) {
        if v != a[0] {
            return false
        }
    }
    return true
}

Upvotes: 1

user142162
user142162

Reputation:

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
}

Upvotes: 18

Related Questions