How to Check if a Slice Contains an Element in Go

Created
Modified

Using contains Function

The following example should cover whatever you are trying to do:

package main

import "fmt"

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

  for _, vs := range s {
    if vs == v {
      return true
    }
  }

  return false
}

func main() {
  s := []string{"Gopher", "Alice", "Bob"}
  fmt.Println(Contains(s, "Bob"))
  fmt.Println(Contains(s, "bob"))
}
true
false

Using slices.Contains Function

Starting with Go 1.18, you can use the slices package – specifically the generic Contains function:

package main

import (
  "fmt"

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

func main() {
  s := []string{"Gopher", "Alice", "Bob"}
  b := slices.Contains(s, "Bob")
  fmt.Println(b)
  b = slices.Contains(s, "bob")
  fmt.Println(b)
}
true
false

Related Tags