find the index of an element in an array in go

To find the index of an element in an array in Go, you can use a for loop to iterate through the array and compare each element with the one you're searching for. Here is an example implementation:

main.go
package main

import "fmt"

func getIndex(arr [5]int, elem int) int {
    for i := 0; i < len(arr); i++ {
        if arr[i] == elem {
            return i
        }
    }
    return -1 // return -1 if element not found
}

func main() {
    arr := [5]int{1, 3, 5, 7, 9}
    elem := 5
    index := getIndex(arr, elem)
    fmt.Println(index) // output: 2
}
354 chars
20 lines

In this example, the getIndex function takes an array arr and an element elem, and returns the index of the first occurrence of elem in arr. If elem is not found in arr, the function returns -1.

The getIndex function uses a for loop to iterate through the array arr. For each element of arr, the function checks if it is equal to elem. If it is, the function returns the index of the element. If none of the elements in arr are equal to elem, the function returns -1.

In the main function, we create an array arr and an element elem. We then call the getIndex function and store the result in the variable index. Finally, we print the value of index to the console. The output of this code should be 2, since the element 5 is located at index 2 in the array.

related categories

gistlibby LogSnag