OneBite.Dev - Coding blog in a bite size

search for a specific element in an array in Go

Code snippet on how to search for a specific element in an array in Go

package main
 
import (
	"fmt"
)
 
func main() {
	arr := []string{"a", "b", "c", "d", "e"}
 
	var search string
	fmt.Print("Search: ")
	_, err := fmt.Scan(&search)
	if err != nil {
		fmt.Println(err)
		return
	}
 
	for i, v := range arr {
		if v == search {
			fmt.Printf("Element found at index %d\n", i)
			return
		}
	}
	fmt.Println("Element not found")
}

This code searches for a specific element in an array of strings. It starts by defining the array, which in this example is five strings. Then a variable “search” is declared, and the user is prompted to enter a search. A loop is then used to iterate through each element of the array, and if the element is equal to the search element, the index is printed and the program ends. If the element is not found, the program prints that the element is not found.

go