Created
January 15, 2020 10:31
-
-
Save gsscoder/9e5b1234ad75490ff5e06de928b12d03 to your computer and use it in GitHub Desktop.
Go generic function to find an array item
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
// "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