如何在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
廣告