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
+5k Golang : The Tao of importing package
+7.3k Android Studio : AlertDialog to get user attention example
+6.9k Golang : Get environment variable
+5k Golang : Calculate half life decay example
+17.3k Golang : Parse date string and convert to dd-mm-yyyy format
+9.1k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+7.9k Golang : HttpRouter multiplexer routing example
+18.7k Golang : Check whether a network interface is up on your machine
+10.8k Golang : Read until certain character to break for loop
+28.1k Golang : Change a file last modified date and time
+5.9k Golang : Scan forex opportunities by Bollinger bands
+33.6k Golang : Create x509 certificate, private and public keys