How to find out element position in slice?

Sorry, there's no generic library function to do this. Go doesn't have a straight forward way of writing a function that can operate on any slice.

Your function works, although it would be a little better if you wrote it using range.

If you happen to have a byte slice, there is bytes.IndexByte.


You can create generic function in idiomatic go way:

func SliceIndex(limit int, predicate func(i int) bool) int {
    for i := 0; i < limit; i++ {
        if predicate(i) {
            return i
        }
    }
    return -1
}

And usage:

xs := []int{2, 4, 6, 8}
ys := []string{"C", "B", "K", "A"}
fmt.Println(
    SliceIndex(len(xs), func(i int) bool { return xs[i] == 5 }),
    SliceIndex(len(xs), func(i int) bool { return xs[i] == 6 }),
    SliceIndex(len(ys), func(i int) bool { return ys[i] == "Z" }),
    SliceIndex(len(ys), func(i int) bool { return ys[i] == "A" }))

Tags:

Slice

Position

Go