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
GO Program to Find the Largest Number Among Three Numbers
How to remove special characters from a string in GoLang?
Interfaces with similar methods in Go Programming Language
Go program to find MX records record of a domain
GO Program to Calculate Sum of Natural Numbers Using for.....Loop
How to change slice item value in Golang?
GO Program to take user input and addition of two strings
Go program to find Forward(A) record of a domain
Sierpinski triangle in Go Programming Language
Example: How to use ReadAtLeast from IO Package in Golang?