Created
April 13, 2020 11:50
-
-
Save sourabh-upadhyay/2544cddcfdad3b56f10c5684ba4e6f6d to your computer and use it in GitHub Desktop.
Find the element in an array in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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