To get the index of a specified element in an array in Go, you can iterate over the array and check each element.
In this example,
arr
with values 10, 20, 30, 40, 50.package main
import (
"fmt"
)
func main() {
arr := []int{10, 20, 30, 40, 50}
specifiedElement := 30
found := false
for index, element := range arr {
if element == specifiedElement {
fmt.Printf("Index of specified element %d is: %d\n", specifiedElement, index)
found = true
break
}
}
if !found {
fmt.Println("Specified element not found in the array")
}
}
Index of specified element 30 is: 2
In this example,
arr
with values 10, 20, 30, 40, 50.package main
import (
"fmt"
)
func main() {
arr := []int{10, 20, 30, 40, 50}
specifiedElement := 60
found := false
for index, element := range arr {
if element == specifiedElement {
fmt.Printf("Index of specified element %d is: %d\n", specifiedElement, index)
found = true
break
}
}
if !found {
fmt.Println("Specified element not found in the array")
}
}
Specified element not found in the array
In this tutorial, we learned How to get the Index of Specified Element in an Array in Go language with well detailed examples.