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
+8.8k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+28.2k Golang : How to verify uploaded file is image or allowed file types
+15.5k Golang : Capture stdout of a child process and act according to the result
+8.5k Golang : interface - when and where to use examples
+16k Golang : Parse date string and convert to dd-mm-yyyy format
+5k Golang : Detect variable or constant type
+7k Golang : Oanda bot with Telegram and RSI example
+18.6k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+4.7k Golang : Error handling methods
+13.9k Golang : How to login and logout with JWT example
+11.8k Golang : Handle or parse date string with Z suffix(RFC3339) example
+14.2k Golang : How to convert(cast) IP address to string?