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
+5.1k Golang : Issue HTTP commands to server and port example
+33.9k Golang : Proper way to set function argument default value
+11.3k Use systeminfo to find out installed Windows Hotfix(s) or updates
+11.2k Golang : How to pipe input data to executing child process?
+14.1k Golang : Check if a file exist or not
+12k Golang : convert(cast) string to integer value
+29.8k Golang : How to get HTTP request header information?
+14.4k Golang : How to determine if user agent is a mobile device example
+8.8k Golang : Find network service name from given port and protocol
+20.1k Swift : Convert (cast) Int to int32 or Uint32
+17.1k Golang : Find file size(disk usage) with filepath.Walk
+11.7k Golang : Verify Linux user password again before executing a program example