Skip to content

Instantly share code, notes, and snippets.

@sourabh-upadhyay
Created April 13, 2020 11:50
Show Gist options
  • Save sourabh-upadhyay/2544cddcfdad3b56f10c5684ba4e6f6d to your computer and use it in GitHub Desktop.
Save sourabh-upadhyay/2544cddcfdad3b56f10c5684ba4e6f6d to your computer and use it in GitHub Desktop.
Find the element in an array in golang
package main
import "fmt"
import "reflect"
func contains(val interface{}, array interface{}) (exists bool, index int) {
exists = false
index = -1
switch reflect.TypeOf(array).Kind() {
case reflect.Slice:
s := reflect.ValueOf(array)
for i := 0; i < s.Len(); i++ {
if reflect.DeepEqual(val, s.Index(i).Interface()) == true {
index = i
exists = true
return
}
}
}
return
}
func main() {
names := []string{"A", "B", "C", "D", "E"}
fmt.Println(contains("A", names))
fmt.Println(contains("G", names))
ints := []int{1, 4, 3, 2, 6}
fmt.Println(contains(3, ints))
fmt.Println(contains(95, ints))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment