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

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

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

package main

import (
	"fmt";

	"golang.org/x/exp/slices"
)

func main() {
	arr := []int{1, 2, 3, 4, 5}
	fmt.Println(slices.Contains(arr, 3))
	fmt.Println(slices.Contains(arr, 6))
}

go-playground

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

使用集合而不是切片

package main

import (
	"fmt";
)

func main() {
	arr := map[int]struct{}{
		1: {},
		2: {},
		3: {},
		4: {},
		5: {},
	}
	_, contains3 := arr[3]
	fmt.Println(contains3)
	_, contains6 := arr[6]
	fmt.Println(contains6)
}

go-playground

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

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

英文:

2 solutions:

Using slices.Contains

package main

import (
	"fmt"

	"golang.org/x/exp/slices"
)

func main() {
	arr := []int{1, 2, 3, 4, 5}
	fmt.Println(slices.Contains(arr, 3))
	fmt.Println(slices.Contains(arr, 6))
}

go-playground

You can find the implementation of slices.Contains here

Using a set instead of a slice

package main

import (
	"fmt"
)

func main() {
	arr := map[int]struct{}{
		1: {},
		2: {},
		3: {},
		4: {},
		5: {},
	}
	_, contains3 := arr[3]
	fmt.Println(contains3)
	_, contains6 := arr[6]
	fmt.Println(contains6)
}

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:

确定