Check if a slice contains a value

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

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:

package main

import (

func main() {
	s := []string{"🌱", "🪡", "🌱"}
	x := "🪡"
	y := "🙈"

	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.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

Subscribe to my Newsletter and Keep Learning.

Gain access to more content and get notified of the latest articles:

I send emails every 1-2 weeks and will keep your data safe. You can unsubscribe at any time.

Hello! I'm the Willem behind

I created this website to help new Go developers, I hope it brings you some value! :)

You can follow me on Twitter/X, LinkedIn or Mastodon.

Thanks for reading!