Golang : Check if item is in slice/array
Problem :
You need to see if an item is inside a slice or array.
Solution :
Golang does not have any builtin function to do this for the moment(March 2015). You have to write a function to iterate over the list and check if the item exist or not in the list.
package main
import (
"fmt"
)
func printslice(slice []string) {
fmt.Println("slice = ", slice)
//for i := range slice {
// fmt.Println(i, slice[i])
//}
}
func stringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}
func main() {
strList := []string{"Hello", "World", "GoodBye", "World", "We", "Love", "Love", "You"}
printslice(strList)
if !stringInSlice("Save", strList) {
fmt.Println("The word Save is not in the list!")
}
if stringInSlice("Love", strList) {
fmt.Println("The word Love is in the list!")
}
}
Output :
slice = [Hello World GoodBye World We Love Love You]
The word Save is not in the list!
The word Love is in the list!
See also : Golang : Delete duplicate items from a slice/array
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.4k Golang : Tell color name with OpenCV example
+5.4k PHP : Shuffle to display different content or advertisement
+20.2k Golang : Convert Unix timestamp to UTC timestamp
+28k Golang : Generate random string
+11k Python : Convert IPv6 address to decimal and back to IPv6
+4.5k Get website traffic ranking with Similar Web or Alexa
+17.1k Golang : Compare floating-point numbers
+6.2k Golang : Gorrila set route name and get the current route name
+15.5k Golang : Find smallest number in array
+17.3k Golang : How to make function callback or pass value from function as parameter?
+10.9k Golang : Qt progress dialog example
+19.4k Golang : Print leading(padding) zero or spaces in fmt.Printf?