golang check if in array
package main
import (
"fmt"
)
func main() {
// Define an array of strings
arr := []string{"apple", "banana", "orange", "grape"}
// Declare a variable to store the item to search
item := "orange"
// Iterate through the array using a for loop
for _, value := range arr {
// Check if the current value in the array matches the item
if value == item {
// If there is a match, print that the item is found
fmt.Println("Item found in the array!")
// Exit the loop since the item is found
break
}
}
// If the loop completes without finding the item, print that it's not in the array
fmt.Println("Item not found in the array.")
}
Explanation:
Array Initialization:
arr := []string{"apple", "banana", "orange", "grape"}
initializes an arrayarr
containing strings "apple," "banana," "orange," and "grape".Item to Search:
item := "orange"
declares a variableitem
that stores the string "orange," which is the item we want to find in the array.For Loop:
for _, value := range arr { ... }
iterates through each element in thearr
array.value
holds the value of each element during each iteration.Comparison:
if value == item { ... }
checks if the current value being iterated (value
) in the array matches theitem
we're searching for.Print Statements:
- If a match is found (
value == item
),"Item found in the array!"
is printed, indicating that the item is present. If the loop completes without finding the item,
"Item not found in the array."
is printed, indicating that the item is not present in the array.Loop Exit:
break
statement is used to exit the loop once the item is found to avoid unnecessary iterations after finding the item.