To check if a specified element is present in an array in Go, you can use a loop to iterate through the array and check each element.
In this example,
numbers
with values 10, 20, 30, 40, 50.for
loop and check each element if it matches the specified element 30.found
to true; otherwise, it remains false.package main
import (
"fmt"
)
func main() {
numbers := []int{10, 20, 30, 40, 50}
found := false
for _, num := range numbers {
if num == 30 {
found = true
break
}
}
fmt.Println("Element 30 is present:", found)
}
Element 30 is present: true
In this example,
fruits
with values 'apple', 'banana', 'cherry'.for
loop and check each element if it matches the specified element 'banana'.found
to true; otherwise, it remains false.package main
import (
"fmt"
)
func main() {
fruits := []string{"apple", "banana", "cherry"}
found := false
for _, fruit := range fruits {
if fruit == "banana" {
found = true
break
}
}
fmt.Println("Element 'banana' is present:", found)
}
Element 'banana' is present: true
In this tutorial, we learned How to check if Specified Element is present in the Array in Go language with well detailed examples.