如何在Go语言中检查切片是否包含某个元素?
许多语言都提供了类似于**indexOf()**的方法,可以查找数组式数据结构中是否存在特定元素。但是,在**Golang**中,没有这样的方法,我们可以简单地使用**for-range**循环来实现。
假设我们有一个字符串切片,我们想找出某个特定字符串是否存在于该切片中。
示例1
考虑以下代码。
package main
import (
"fmt"
)
func Contains(sl []string, name string) bool {
for _, value := range sl {
if value == name {
return true
}
}
return false
}
func main() {
sl := []string{"India", "Japan", "USA", "France"}
countryToCheck := "Argentina"
isPresent := Contains(sl, countryToCheck)
if isPresent {
fmt.Println(countryToCheck, "is present in the slice named sl.")
} else {
fmt.Println(countryToCheck, "is not present in the slice named sl.")
}
}在上面的代码中,我们试图查找值为“**阿根廷**”的字符串是否出现在切片“**sl**”中。
输出
如果我们运行命令**go run main.go**,则会在终端中得到以下输出。
Argentina is not present in the slice named sl.
我们还可以打印在切片中遇到元素的索引。
示例2
考虑以下代码。
package main
import (
"fmt"
)
func Contains(sl []string, name string) int {
for idx, v := range sl {
if v == name {
return idx
}
}
return -1
}
func main() {
sl := []string{"India", "Japan", "USA", "France"}
countryToCheck := "USA"
index := Contains(sl, countryToCheck)
if index != -1 {
fmt.Println(countryToCheck, "is present in the slice named sl at index", index)
} else {
fmt.Println(countryToCheck, "is not present in the slice named sl.")
}
}输出
如果我们运行命令**go run main.go**,则会在终端中得到以下输出。
USA is present in the slice named sl at index 2
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP