What would be the most elegant way to check if every item in a slice meets some condition? In my specific scenario, I have a slice of bytes: [16]byte. I need to check if all bytes are 0.
In JS, for example, I would do something like that:
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
What's the cleanest and most straightforward way to do this in Go?
For readability and flexibility (e.g. if you need to operate on types other than byte
), you may benefit from writing a small All
generic function that
true
if and only if the predicate is satisfied for all elements of the slice.You'll then be free to put that generic function to use with different slices and predicates.
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
}
No need to create a library for that All
function, though; a little copying is better than a little dependency.