在数组中找到一个元素的下标,找不到返回-1

在javascript中可以这样写:

var a = ['a','b','c','d']
console.log(a.indexOf('c')) // 2

* index.go


import (
	"fmt"
	"strings"
)

type CompareFunc func(interface{}, interface{}) int

func indexOf(a []interface{}, e interface{}, cmp CompareFunc) int {
	n := len(a)
	var i int = 0;
	for ; i < n; i++ {
		if cmp(e, a[i]) == 0 {
			return i;
		}
	}
	return -1;
}

func main() {
	as := []string{"apple", "banana", "lime", "橘子", "orange", "橙子", "pineapple", "vine"}
	// convert []string to []interface
	ai := make([]interface{}, len(as))
	for i, v := range as {
		ai[i] = v
	}

	// Find index of  "orange" in array
	fmt.Printf("orange index=%d\n", indexOf(ai, "橙子", func (a interface{}, b interface{}) int {
		s1 := a.(string)
		s2 := b.(string)
		return strings.Compare(s1, s2)
	}));
}

* test:

$ go run index.go
orange index=5
 

橙子 所在数组元素下标为5