Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Created January 15, 2020 10:31
Show Gist options
  • Save gsscoder/9e5b1234ad75490ff5e06de928b12d03 to your computer and use it in GitHub Desktop.
Save gsscoder/9e5b1234ad75490ff5e06de928b12d03 to your computer and use it in GitHub Desktop.
Go generic function to find an array item
// "generic" function to find an array item
package main
import (
"fmt"
"reflect"
)
func main() {
ints := make([]int, 5)
ints[0] = 10
ints[1] = 20
ints[2] = 30
ints[3] = 40
ints[4] = 50
fmt.Printf("%d\n", find(ints, 30)) // output: 2
fmt.Printf("%d\n", find(ints, 90)) // output: -1
}
func find(array interface{}, item interface{}) int {
arrayValue := reflect.ValueOf(array)
itemValue := reflect.ValueOf(item)
for i := 0; i < arrayValue.Len(); i++ {
if arrayValue.Index(i).Interface() == itemValue.Interface() {
return i
}
}
return -1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment