Searching an element of int type in slice of ints in Golang


Slices are an essential feature of Go programming language that allows you to store and manipulate an ordered collection of elements. Slices are similar to arrays, but unlike arrays, they are dynamic and can be resized. In Go, you can perform a search operation on a slice to find an element or a set of elements. This article will guide you through the process of searching for an element of int type in a slice of ints in Go.

Searching an element of int type in slice of ints in Golang

To search for an element of int type in a slice of ints, you can use the built-in for loop.

Example

Here's an example code −

package main

import "fmt"

func main() {
   slice := []int{1, 2, 3, 4, 5}
   var searchElement int = 3

   for i := range slice {
      if slice[i] == searchElement {
         fmt.Printf("Element %d found at index %d\n", searchElement, i)
         break
      }
   }
}

Output

In the above code, we have a slice of ints, slice with elements 1, 2, 3, 4, and 5. We want to search for the element with a value of 3 in the slice. We declare a variable searchElement with a value of 3. We then use a for loop to iterate through each element of the slice. Inside the for loop, we use an if statement to compare each element of the slice with the searchElement. If we find the element in the slice, we print a message with the index of the element.

Element 3 found at index 2

In the above example, the element with a value of 3 is present in the slice at index 2, and the message displays the same.

Conclusion

Searching for an element of int type in a slice of ints in Go is straightforward. You can use the built-in for loop to iterate through each element of the slice and compare it with the search element. If the element is found, you can display its index or any other message as per the requirement.

Updated on: 18-Apr-2023

55 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements