Go:检查切片中的每个项是否满足条件

huangapple go评论81阅读模式
英文:

Go: Check if every item in a slice meets a condition

问题

在Go语言中,可以使用循环来检查切片中的每个元素是否满足条件。对于你的特定情况,你可以使用以下代码来检查一个字节切片中的所有字节是否都为0:

package main

import "fmt"

func main() {
    byteArray := [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0} // 可以看作是一个字节切片

    isEmpty := true
    for _, b := range byteArray {
        if b != 0 {
            isEmpty = false
            break
        }
    }

    fmt.Println(isEmpty) // false
}

这段代码使用了一个for循环来遍历字节切片中的每个元素。如果发现任何一个元素不等于0,则将isEmpty设置为false并跳出循环。如果所有元素都为0,则isEmpty保持为true。最后,打印isEmpty的值。

这是一种简洁而直接的方法来检查切片中的每个元素是否满足条件。

英文:

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?

答案1

得分: 2

为了提高可读性和灵活性(例如,如果您需要操作除了byte之外的其他类型),您可以编写一个小的All通用函数,它具有以下特点:

  • 接受一个切片和一个对该切片的元素类型的谓词,
  • 当且仅当谓词对切片的所有元素都满足时返回true

然后,您可以自由地将该通用函数与不同的切片和谓词一起使用。

package main

import "fmt"

func main() {
	bs := []byte{15: 1} // 16个字节的切片,除了最后一个字节外,其他都是零
	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
}

Playground

不需要为All函数创建一个库,一点复制比一点依赖更好

英文:

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

  • accepts a slice and a predicate on the element type of that slice, and
  • returns 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
}

(Playground)

No need to create a library for that All function, though; a little copying is better than a little dependency.

答案2

得分: 2

使用bytes包会很容易,这里有一个示例:

func main() {
    n := []byte{0,0,0,0,0,0,0}
    b := bytes.ContainsRune(n, 1)
    fmt.Println(b)
}

在bytes包中,有多个方法可以用来检查结果,比如检查字符、多个包含等等。

英文:

It would be easy if you use the bytes package, here is an example :

func main() {
	n := []byte{0,0,0,0,0,0,0}
	b := bytes.ContainsRune(n, 1)
	fmt.Println(b)
}

In bytes package there are multiple methods you can call for your result, like checking char, or multiple contains etc.

答案3

得分: 1

最直接的方法是使用基于范围的for循环,因为据我所知,Go语言没有类似于.ForEach的内置函数。

如果你不需要索引,可以在循环中省略它,你将得到类似的结果:

isEmpty := true
for _, val := range uint8Array {
    if val != 0 {
        isEmpty=false
        break
    }
}

fmt.Println(isEmpty)

如果你需要多次使用该函数,你也可以将其定义为一个独立的函数:

func IsEmpty(arr *[]any) bool {
    for _, val := range *arr {
        if val != 0 {
            return false
        }
    }
    
    return true
}

尽管最后一个方法可能会对某些数据类型造成问题。

英文:

The most straightforward way is to use a range-based for loop, since as far as I'm aware, Go doesn't have built-in function similar to .ForEach.

If you don't need an index, you can omit it from the loop and you will have something similar:

isEmpty := true
for _, val := range uint8Array {
    if val != 0 {
        isEmpty=false
        break
    }
}

fmt.Println(isEmpty)

If you use the function repeatedly, you can define it as your own separate function as well.

func IsEmpty(arr *[]any) bool {
    for _, val := range *arr {
        if val != 0 {
            return false
        }
    }
    
    return true
}

Although the last one might cause issues for some data types.

huangapple
  • 本文由 发表于 2023年2月13日 19:08:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75435042.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定