如何检查x是否在一个数组中,而不遍历整个数组,使用Go?语言中有这样的结构吗?
如在Python中:
if "x" in array:
# do something
如何检查x是否在一个数组中,而不遍历整个数组,使用Go?语言中有这样的结构吗?
如在Python中:
if "x" in array:
# do something
当前回答
如果列表包含静态值,则另一种解决方案。
例:从有效值列表中检查有效值:
func IsValidCategory(category string) bool {
switch category {
case
"auto",
"news",
"sport",
"music":
return true
}
return false
}
其他回答
在Go 1.18+中,您现在可以声明泛型Contains函数,该函数也在实验性slice函数中实现。它适用于任何类似的类型
func Contains[T comparable](arr []T, x T) bool {
for _, v := range arr {
if v == x {
return true
}
}
return false
}
像这样使用它:
if Contains(arr, "x") {
// do something
}
// or
if slices.Contains(arr, "x") {
// do something
}
我在这里找到的
在Go中没有内置的操作符来做这件事。你需要遍历数组。你可以编写自己的函数来实现,就像这样:
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
或者在Go 1.18或更新版本中,你可以使用切片。包含(来自golang.org/x/exp/slices)。
如果你想在不遍历整个列表的情况下检查成员关系,你需要使用map而不是数组或slice,如下所示:
visitedURL := map[string]bool {
"http://www.google.com": true,
"https://paypal.com": true,
}
if visitedURL[thisSite] {
fmt.Println("Already been here.")
}
这段话摘自《Go编程:为21世纪创建应用程序》一书:
Using a simple linear search like this is the only option for unsorted data and is fine for small slices (up to hundreds of items). But for larger slices—especially if we are performing searches repeatedly—the linear search is very inefficient, on average requiring half the items to be compared each time. Go provides a sort.Search() method which uses the binary search algorithm: This requires the comparison of only log2(n) items (where n is the number of items) each time. To put this in perspective, a linear search of 1000000 items requires 500000 comparisons on average, with a worst case of 1000000 comparisons; a binary search needs at most 20 comparisons, even in the worst case.
files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.Search(len(files),
func(i int) bool { return files[i] >= target })
if i < len(files) && files[i] == target {
fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}
https://play.golang.org/p/UIndYQ8FeW
如果列表包含静态值,则另一种解决方案。
例:从有效值列表中检查有效值:
func IsValidCategory(category string) bool {
switch category {
case
"auto",
"news",
"sport",
"music":
return true
}
return false
}
上面使用sort的例子很接近,但是在字符串的情况下只需使用SearchString:
files := []string{"Test.conf", "util.go", "Makefile", "misc.go", "main.go"}
target := "Makefile"
sort.Strings(files)
i := sort.SearchStrings(files, target)
if i < len(files) && files[i] == target {
fmt.Printf("found \"%s\" at files[%d]\n", files[i], i)
}
https://golang.org/pkg/sort/#SearchStrings