猿问

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

我需要创建一个函数:


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

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


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


隔江千里
浏览 183回答 1
1回答

守候你守候我

我不确定您反转切片的过程是什么,但这没有必要。最简单的算法是检查第一个之后的所有元素是否等于第一个:func allSameStrings(a []string) bool {&nbsp; &nbsp; for i := 1; i < len(a); i++ {&nbsp; &nbsp; &nbsp; &nbsp; if a[i] != a[0] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return false&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return true}
随时随地看视频慕课网APP

相关分类

Go
我要回答