How to check if an item exists in Slice in Golang?
To determine if a specified item is present in a slice iterate slice item and check using if condition.
Example
package main
import (
"fmt"
"reflect"
)
func main() {
var strSlice = []string{"India", "Canada", "Japan", "Germany", "Italy"}
fmt.Println(itemExists(strSlice, "Canada"))
fmt.Println(itemExists(strSlice, "Africa"))
}
func itemExists(slice interface{}, item interface{}) bool {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
panic("Invalid data-type")
}
for i := 0; i < s.Len(); i++ {
if s.Index(i).Interface() == item {
return true
}
}
return false
}
Most Helpful This Week
How do you handle HTTP server shutdown gracefully in Go?
Golang program for implementation of Interpolation Search
Golang read csv file into struct
How do you read cookies in an HTTP request with an HTTP client in Go?
GO language program with example of Sort Functions for integer, strings and float64 data type
How to create Slice of Struct in Golang?
Syntax error: unexpected <token> error in Golang
How do you handle HTTP server health checks in Go?
Golang program for implementation of Floyd–Warshall Algorithm
Golang program for implementation of Shell Sort