How to check if an element is inside a slice in Golang

Overview

Slices are a built-in data type in Golang similar to arrays, except that a slice has no specified length. All elements within a slice must have the same type.

The code below shows how to declare a slice literal with the string type specification:

newSlice := []string{"a", "b", "c", "d"}

How to check if a slice contains an element

To check if a particular element is present in a slice object, we need to perform the following steps:

  1. Use a for loop to iterate over each element in the slice.
  2. Use the equality operator (==) to check if the current element matches the element you want to find.

The code below demonstrates this process.

package main
import (
"fmt"
)
func main(){
// initialize a slice literal
newSlice := []string{"a", "b", "c", "d"}
fmt.Println("The original slice is:", newSlice)
// initialize the strings to search for
searchString := "c"
// initialize a found flag
found := false
// iterate over the slice
for i, v := range newSlice {
// check if the strings match
if v == searchString {
found = true
fmt.Println("The slice contains", searchString, "at index", i)
break
}
}
// if string not found
if found == false {
fmt.Println("The slice does not contain", searchString)
}
}

Explanation

In the code above:

  • In line 44, we import the fmt package for printing.

  • In line 1010, we initialize a slice literal of the string type called newSlice. At the time of declaration, newSlice contains 44 values.

  • Then, the code initializes the string to check the slice for in line 1414. We also declare a boolean variable found to serve as a flag that indicates whether or not the searchString is present in newSlice.

  • The for loop in line 1919 proceeds to iterate over each value in newSlice.

  • The if statement in line 2323 checks if the current element matches searchString. If both strings match, found is set to true. The code prints the index at which the element was found and the loop is terminated.

  • If the slice does not contain searchString, the loop finishes its execution. However, the value of found would still be false. Consequently, the if statement in line 3131 checks whether or not the string was found.

Free Resources