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
+9.1k Golang : Setting variable value with ldflags
+13.2k Golang : How to pass map to html template and access the map's elements
+31.2k Golang : Convert []string to []byte examples
+20k Golang : Create and resolve(read) symbolic links
+10.1k Golang : Generate random elements without repetition or duplicate
+14.8k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+14k Golang : Basic authentication with .htpasswd file
+5.8k Nginx : Password protect a directory/folder
+27.2k Golang : Read, Write(Create) and Delete Cookie example
+12.5k Golang : Image to ASCII art example
+8k Golang : Gorilla web tool kit schema example