Golang 如何检查一个片断是否包含一个元素

Golang 如何检查一个片断是否包含一个元素

许多语言都提供了类似 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.")
   }
}
Go

在上面的代码中,我们试图找到值为 ” Argentina “的字符串是否存在于片断 ” sl “中。

输出

如果我们运行命令 go run main.go ,那么我们将在终端得到以下输出。

Argentina is not present in the slice named sl.
Go

我们也可以打印出我们在切片中遇到的元素的索引。

例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

输出

如果我们运行命令 go run main.go ,我们将在终端得到以下输出。

USA is present in the slice named sl at index 2
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册