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
+25.7k Golang : missing Mercurial command
+7.5k Golang : Check to see if *File is a file or directory
+7.4k Golang : Convert source code to assembly language
+9.1k Golang : Get curl -I or head data from URL example
+19.2k Golang : Execute shell command
+7.3k Golang : How to iterate a slice without using for loop?
+4.8k PHP : Extract part of a string starting from the middle
+9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+5.5k How to check with curl if my website or the asset is gzipped ?
+4.5k Java : Generate multiplication table example
+18.4k Golang : How to get hour, minute, second from time?
+6.2k Golang : Scan forex opportunities by Bollinger bands