Check if two slices are equal

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

If you use the == or != comparison operators you can only compare slices to nil. So how do you check if two slices are equal?

Well.. that depends on what you mean by โ€œequal slicesโ€. But often you want to check if slices are of the same length and have equal elements at the same indices.

Depending on your Go version you can:

These functions compare the elements using ==. Depending on your situation you may want to compare the elements in a different way. The EqualFunc 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 EqualSlices function. See the example below:

main.go
package main

import (
	"fmt"
	"slices"
)

func main() {
	x := []string{"๐Ÿ™ˆ", "๐Ÿ™‰", "๐Ÿ™Š"}
	y := []string{"๐Ÿ™ˆ", "๐Ÿฆ"}

	fmt.Println("slices.Equal:")
	fmt.Println("x equal to y?", slices.Equal(x, y))
	fmt.Println("y equal to x?", slices.Equal(y, x))
	fmt.Println("x equal to x?", slices.Equal(x, x))
	fmt.Println("y equal to y?", slices.Equal(y, y))

	fmt.Println("---")

	fmt.Println("EqualSlices:")
	fmt.Println("x equal to y?", EqualSlices(x, y))
	fmt.Println("y equal to x?", EqualSlices(y, x))
	fmt.Println("x equal to x?", EqualSlices(x, x))
	fmt.Println("y equal to y?", EqualSlices(y, y))
}

// EqualSlices checks if two slices have equal contents.
// For two slices to be equal:
// - They need to have the same number of elements.
// - Each element must be equal using the == operator.
func EqualSlices(s1, s2 []string) bool {
	if len(s1) != len(s2) {
		return false
	}

	for i, v := range s1 {
		if s2[i] != v {
			return false
		}
	}

	return true
}

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.