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
+7.7k Golang : What fmt.Println() can do and println() cannot do
+8.2k PHP : How to parse ElasticSearch JSON ?
+9.1k Golang : Detect Pascal, Kebab, Screaming Snake and Camel cases
+31.8k Golang : Math pow(the power of x^y) example
+28k Golang : Change a file last modified date and time
+17.9k Golang : Get command line arguments
+26.3k Golang : Encrypt and decrypt data with AES crypto
+24.1k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+5.3k PHP : Fix Call to undefined function curl_init() error
+30.6k Golang : Calculate percentage change of two values
+12.5k Golang : Convert int(year) to time.Time type