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:

  1. Array Initialization: arr := []string{"apple", "banana", "orange", "grape"} initializes an array arr containing strings "apple," "banana," "orange," and "grape".

  2. Item to Search: item := "orange" declares a variable item that stores the string "orange," which is the item we want to find in the array.

  3. For Loop: for _, value := range arr { ... } iterates through each element in the arr array. value holds the value of each element during each iteration.

  4. Comparison: if value == item { ... } checks if the current value being iterated (value) in the array matches the item we're searching for.

  5. Print Statements:

  6. If a match is found (value == item), "Item found in the array!" is printed, indicating that the item is present.
  7. 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.

  8. Loop Exit: break statement is used to exit the loop once the item is found to avoid unnecessary iterations after finding the item.