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.go354 chars20 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.
gistlibby LogSnag