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" }))

You could write a function;

func indexOf(element string, data []string) (int) {
   for k, v := range data {
       if element == v {
           return k
       }
   }
   return -1    //not found.
}

This returns the index of a character/string if it matches the element. If its not found, returns a -1.


There is no library function for that. You have to code by your own.