if you have predefined type like []int
or []string
and do not want to convert to []interface{}
see this working sample code (without using reflect
):
package main
import "fmt"
func find(s []int, f func(int) bool) int {
for i, item := range s {
if f(item) {
return i
}
}
return -1
}
func findString(s []string, f func(string) bool) int {
for i, item := range s {
if f(item) {
return i
}
}
return -1
}
func main() {
s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(find(s, func(a int) bool { return a == 5 })) //5
strs := []string{"A", "B", "C"}
fmt.Println(findString(strs, func(a string) bool { return a == "B" })) //1
}
or you may use reflect
,like this working sample code:
package main
import "fmt"
import "reflect"
func find(slice interface{}, f func(interface{}) bool) int {
switch reflect.TypeOf(slice).Kind() {
case reflect.Slice:
values := reflect.Indirect(reflect.ValueOf(slice))
for i := 0; i < values.Len(); i++ {
if f(values.Index(i).Interface()) {
return i
}
}
}
return -1
}
func main() {
a := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(find(a, func(i interface{}) bool { return i == 5 })) //5
b := []string{"A", "B", "C"}
fmt.Println(find(b, func(i interface{}) bool { return i == "B" })) //1
}
output:
5
1
I hope this helps.