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:
- In 1.21, use the
Equalfunction in theslicespackage in the standard library. - For earlier versions, you can find the same function in the experimental
slicespackage.
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:
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
}
Career choice: Learn skills to mitigate the upcoming AI privacy disaster*
Join 800+ devs reading my newsletter
*Everyone and their mother is sending sensitive data to AI systems with little concern for their privacy. If you read the fineprint, vendors and platforms actually offer very little guarantees. It's a matter of time before it goes wrong.
From March 2026 onwards, I'll be writing about development of verifiably-secure services using OpenPCC.