Check if a slice contains a value

Avatar of the author Willem Schots
6 Jul, 2023 (Updated 22 Jan, 2024)
~2 min.
RSS

Some languages have an in operator that checks if a collection contains a certain value, Go does not.

In Go the same functionality is provided by a Contains function.

Depending on your Go version you can use a different approach:

These functions compare the slice values using ==. Depending on your situation you may want to compare in a different way. The ContainsFunc function allows you to specify a custom comparison function.

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
}

Make privacy claims you can back up

Join 800+ subscribers.
One email every few weeks.

I share what I learn building privacy-friendly systems. From confidential computing to Verbond and the occasional Go tip or trick. You can unsubscribe at any time.

A photo of Willem

Written by Willem Schots

I help teams prove what happens to their users' data, and I'm building Verbond, which shows where data can go before third-party code runs.

This site started as a place to learn Go. Most posts are now about privacy-friendly and verifiable systems, with the occasional Go post in between.

Want to talk about your system? Book a 30-minute call, or follow me on Bluesky and LinkedIn.