检查每个切片中是否包含值数字的Go代码。

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

Checking Contains value number in each of slice Go

问题

在GO语言中,有没有一种简单的方法来检查每个切片中是否包含number值,而不使用for-range或for slice循环?

英文:

Is there an easy way to checking contains number value in each of slice using GO Lang, such that without for-range or for slice?

答案1

得分: 1

2种解决方案:

使用slices.Contains

  1. package main
  2. import (
  3. "fmt";
  4. "golang.org/x/exp/slices"
  5. )
  6. func main() {
  7. arr := []int{1, 2, 3, 4, 5}
  8. fmt.Println(slices.Contains(arr, 3))
  9. fmt.Println(slices.Contains(arr, 6))
  10. }

go-playground

你可以在这里找到slices.Contains的实现。

使用集合而不是切片

  1. package main
  2. import (
  3. "fmt";
  4. )
  5. func main() {
  6. arr := map[int]struct{}{
  7. 1: {},
  8. 2: {},
  9. 3: {},
  10. 4: {},
  11. 5: {},
  12. }
  13. _, contains3 := arr[3]
  14. fmt.Println(contains3)
  15. _, contains6 := arr[6]
  16. fmt.Println(contains6)
  17. }

go-playground

这里了解更多关于Go中的映射(map),以及如何使用映射创建集合的信息。

希望对你有帮助 检查每个切片中是否包含值数字的Go代码。

英文:

2 solutions:

Using slices.Contains

  1. package main
  2. import (
  3. "fmt"
  4. "golang.org/x/exp/slices"
  5. )
  6. func main() {
  7. arr := []int{1, 2, 3, 4, 5}
  8. fmt.Println(slices.Contains(arr, 3))
  9. fmt.Println(slices.Contains(arr, 6))
  10. }

go-playground

You can find the implementation of slices.Contains here

Using a set instead of a slice

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func main() {
  6. arr := map[int]struct{}{
  7. 1: {},
  8. 2: {},
  9. 3: {},
  10. 4: {},
  11. 5: {},
  12. }
  13. _, contains3 := arr[3]
  14. fmt.Println(contains3)
  15. _, contains6 := arr[6]
  16. fmt.Println(contains6)
  17. }

go-playground

Read more about maps in go here and how to create a set using maps here

Hope this helps 检查每个切片中是否包含值数字的Go代码。

huangapple
  • 本文由 发表于 2022年9月2日 09:23:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/73576907.html
匿名

发表评论

匿名网友

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

确定