检查切片中的所有项目是否相等

XXX*_*XXX 3 equality go slice

我需要创建一个函数:

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
Run Code Online (Sandbox Code Playgroud)

我能想到的唯一方法是反转切片,并比较切片和反转切片.

有没有更好的方法来做到这一点,语法好,效率更高?

Tim*_*per 11

我不确定你的切换过程是什么,但这是不必要的.最简单的算法是检查第一个之后的所有元素是否等于第一个:

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