How to Check if a Slice Contains an Element in Golang

To check if a slice contains an element in Golang, you can use either the “slice.Contains()” function or “for loop”.

Method 1: Using the slice.Contains() function

Starting with version 1.18, Go introduces a new function called a slice.Contains() that checks if a slice contains a specific element.

Syntax

func Contains[E comparable](s []E, v E) bool

Parameters

(s []E, v E): This is the parameter list for the function. The function takes two arguments: s, which is a slice of E (i.e., it can be a slice of any comparable type), and v, which is a single value of type E.

Return value

The Contains() function will return a boolean value.

Example

If the package “golang.org/x/exp/slices” is not installed on your system, then you can use the below command to install it manually.

go get golang.org/x/exp/slices

Now, you can import it into your program file and use its Contains() method.

package main

import (
  "fmt"

  "golang.org/x/exp/slices"
)

func main() {
  s := []int{11, 21, 19, 46, 50}
  fmt.Println(slices.Contains(s, 19))
  fmt.Println(slices.Contains(s, 52))
}

Output

true
false

You can see that the slices.Contains() function takes a slice and a value of any comparable type, and it will return a boolean value suggesting whether the value is found within the slice.

Method 2: Using for loop

You can use the “for loop” to check the input value against the elements of the slice and determine whether the slice contains it.

Example

package main

import "fmt"

func contains(s []int, elem int) bool {
  for _, a := range s {
    if a == elem {
      return true
    }
  }
  return false
}

func main() {
  s := []int{11, 21, 19, 46, 50}
  fmt.Println(contains(s, 19))
  fmt.Println(contains(s, 52))
}

Output

true
false

In this example, we created a user-defined contains() function that takes a slice of integers and an integer as parameters. It loops over the slice and checks each element to see if it equals the specified integer. If it finds a match, it returns true. It returns false if it doesn’t find a match after checking all elements.