Golang check if array element exists


This Go program checks whether an element exists in an array or not. The program takes an array and an item as input arguments, and it returns a boolean value indicating whether the item exists in the array or not.

The program uses the reflect package in Go to determine the kind of data type of the input array. If the input is not an array, the program panics with an "Invalid data-type" error.

The itemExists function in the program uses a loop to iterate through the elements of the input array. It uses the Index method of the reflect.Value type to access the value of the array element at each index. It then compares the value with the input item using the Interface method of reflect.Value. If a match is found, the function returns true, indicating that the item exists in the array. If no match is found, the function returns false.

In the main function, the program creates an array of strings and calls the itemExists function twice to check whether the items "Canada" and "Africa" exist in the array. The program prints the return values of the function calls, which are either true or false, depending on whether the items exist in the array or not.

Example

package main

import (
	"fmt"
	"reflect"
)

func main() {
	strArray := [5]string{"India", "Canada", "Japan", "Germany", "Italy"}
	fmt.Println(itemExists(strArray, "Canada"))
	fmt.Println(itemExists(strArray, "Africa"))
}

func itemExists(arrayType interface{}, item interface{}) bool {
	arr := reflect.ValueOf(arrayType)

	if arr.Kind() != reflect.Array {
		panic("Invalid data-type")
	}

	for i := 0; i < arr.Len(); i++ {
		if arr.Index(i).Interface() == item {
			return true
		}
	}

	return false
}

Output

true
false
Most Helpful This Week