Sometimes you need to find the index of a value in a slice, and often you’re only interested in the first occurrence of that value.
This is typically done using an Index function, which returns the index of the value in the slice or -1 when it’s not found.
Depending on your Go version you can use a different approach:
- In 1.21, you can use the
Indexfunction in theslicespackage in the standard library. - For earlier versions, you can find the same function in the experimental
slicespackage.
These functions compare the slice values using ==. Depending on your situation you may want to compare in a different way. The IndexFunc function allows you to specify a custom comparison function.
If you are using a Go version that does not support generics, you can always implement your own Index function. See the example below.
package main
import (
"fmt"
"slices"
)
func main() {
s := []string{"🌱", "🪡", "🌱"}
x := "🪡"
y := "🙈"
fmt.Println("slices.Index:")
fmt.Printf("index of \"%s\"? %v\n", x, slices.Index(s, x))
fmt.Printf("index of \"%s\"? %v\n", y, slices.Index(s, y))
fmt.Println("---")
fmt.Println("Index:")
fmt.Printf("index of \"%s\"? %v\n", x, Index(s, x))
fmt.Printf("index of \"%s\"? %v\n", y, Index(s, y))
}
// Index returns the index of the first occurrence of v in s.
// Index returns -1 if v is not found in s.
func Index(s []string, v string) int {
for i, vs := range s {
if vs == v {
return i
}
}
return -1
}
Make privacy claims you can back up
Join 800+ subscribers.
One email every few weeks.
I share what I learn building privacy-friendly systems. From confidential computing to Verbond and the occasional Go tip or trick. You can unsubscribe at any time.
Written by Willem Schots
I help teams prove what happens to their users' data, and I'm building Verbond, which shows where data can go before third-party code runs.
This site started as a place to learn Go. Most posts are now about privacy-friendly and verifiable systems, with the occasional Go post in between.
Want to talk about your system? Book a 30-minute call, or follow me on Bluesky and LinkedIn.