Finding the index of an element in a slice is a common task in Go programming. This snippet demonstrates how to locate an element and retrieve its position.
The traditional approach uses a simple loop to iterate through the slice and compare each element with the target value. When a match is found, we store the index and break out of the loop. If no match is found, the index remains -1.
As of Go 1.21+, the standard library includes slices.Index() which provides a convenient built-in function for this operation. The manual loop approach shown here is useful for understanding the underlying logic and works with all Go versions. For modern code, consider using the slices package for cleaner, more maintainable implementations.