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 to read current directory using Readdir?
How do you send an HTTP GET request with an HTTP client in Go?
Print inverted full pyramid using star
Copy Struct Type Using Value and Pointer Reference
Golang panic recover example
Convert Float32 to Float64 and Float64 to Float32
Example to compare Println vs Printf
How do you handle HTTP errors in Go?
How to create an empty Slice in Golang?
Pascal triangle in Go Programming Language