Check if Array contains Specific Element
To check if array contains a specific element in Go, iterate over elements of array using a for loop, and check for the equality of values using equal to operator. If there is a match, we may stop the search and conclude that the element in present in the array.
Example
In the following program, we take an integer array arr
of size 5
. We check if the element 40
is present in this array.
example.go
</>
Copy
package main
import "fmt"
func main() {
arr := [5]int{10, 20, 30, 40, 50}
var element int = 40
var result bool = false
for _, x := range arr {
if x == element {
result = true
break
}
}
if result {
fmt.Print("Element is present in the array.")
} else {
fmt.Print("Element is not present in the array.")
}
}
Output
Element is present in the array.
Conclusion
In this Golang Tutorial, we learned how to find if an array contains a given element, with the help of example programs.