Golang doesn’t have a built-in function to find index of the element in slice.

I found a great suggestion here.

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


listOfStrings := []string{"test", "test2"}
index := SliceIndex(len(listOfStrings), func(i int) bool { return listOfStrings[i] == "test"}) // => 0

It makes use of functional options, which sounds quite powerful. Definitely, I will talk about it in another note.

You can run it by yourself in this playground. https://go.dev/play/p/FLQlyS9BLd1


discussion