检查切片中的每个项目是否满足某些条件的最优雅的方法是什么?在我的特定场景中,我有一个字节片:[16]byte。我需要检查所有字节是否都是 0。
例如,在 js 中,我会做类似的事情:
const uint8Array = new Uint8Array([0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0])//Can be thought of as an array of "bytes" const isEmpty = uint8Array.every(byte=>byte === 0)//Check that every "byte" is zero console.log(isEmpty)//false
在 go 中执行此操作最干净、最直接的方法是什么?
为了可读性和灵活性(例如,如果您需要对 byte
以外的类型进行操作),您可能会受益于编写一个小的 all
通用函数
true
。然后您就可以自由地将通用函数与不同的切片和谓词一起使用。
package main import "fmt" func main() { bs := []byte{15: 1} // slice of 16 bytes, all but the last one of which are zero isZero := func(b byte) bool { return b == 0 } fmt.Println(All(bs, isZero)) // false } func All[T any](ts []T, pred func(T) bool) bool { for _, t := range ts { if !pred(t) { return false } } return true }
(游乐场)
不过,无需为 all
函数创建库; 一点复制胜过一点依赖。