How to check if a slice contains a value
Published Thu 6 Jul, 2023
Last updated Wed 16 Aug, 2023
Some languages have an in
operator that checks if a collection contains a certain value. Go does not.
To achive the same functionality you have several options depending on your version.
Depending on your Go version you can use a different approach:
- In 1.21 and later, you can use the
Contains
function in theslices
package in the standard library. - For earlier versions, you can find the same function in the experimental
slices
package.
If you are using a Go version that does not support generics, you can always implement your own SliceContains
function. See the example below:
main.go
package main
import (
"fmt"
"slices"
)
func main() {
s := []string{"🌱", "🪡", "🌱"}
x := "🪡"
y := "🙈"
fmt.Println("slices.Contains:")
fmt.Printf("s contains \"%s\"? %v\n", x, slices.Contains(s, x))
fmt.Printf("s contains \"%s\"? %v\n", y, slices.Contains(s, y))
fmt.Println("---")
fmt.Println("SliceContains:")
fmt.Printf("s contains \"%s\"? %v\n", x, SliceContains(s, x))
fmt.Printf("s contains \"%s\"? %v\n", y, SliceContains(s, y))
}
// SliceContains returns true if s contains v.
func SliceContains(s []string, v string) bool {
for _, vs := range s {
if vs == v {
return true
}
}
return false
}
Stay in the loop, subscribe to my newsletter.
for _, f := range []string{
"🏋 Excercises and solutions",
"🔥 Subscriber-only content",
"💌 New posts in your inbox",
"💸 Discounts",
} {
you.Enjoy(f)
}