How to Compare Slice Equality in Go
Comparing the equality of two different slices is often necessary when you need to determine whether the contents of the slices are the same or if they exhibit some specific relationship. In Go, two slices are deemed equal if they possess the same length and contain matching elements in the same sequence.
Attempting to use the ==
operator to compare the equality of two slices
results in a compilation error. Thus, the comparison process necessitates
iterating through the elements of both slices and individually assessing their
equivalence.
There are three primary ways to compare slice equality in Go, as enumerated below:
1. Using slices.Equal()
In Go v1.21, the generic slices
package
was introduced to make several slice operations much easier. One of its exported
methods is Equal()
which helps you compare the equality of two slices:
package main
import (
"fmt"
"slices"
)
func main() {
slice1 := []int{1, 2, 3}
slice2 := []int{1, 2, 3}
slice3 := []int{1, 2, 3, 4, 5}
fmt.Println(slices.Equal(slice1, slice2)) // true
fmt.Println(slices.Equal(slice1, slice3)) // false
}
If you’re running a Go release between v1.18 and v1.20, you can use the
x/exp/slices package instead. It
works the same way as the built-in slices
package above.
package main
import (
"fmt"
"golang.org/x/exp/slices"
)
func main() {
slice1 := []int{1, 2, 3}
slice2 := []int{1, 2, 3}
slice3 := []int{1, 2, 3, 4, 5}
fmt.Println(slices.Equal(slice1, slice2)) // true
fmt.Println(slices.Equal(slice1, slice3)) // false
}
2. Using reflect.DeepEqual()
The reflect
package also exposes the DeepEqual()
function which can be used
to compare the equality of various data structures including slices:
package main
import (
"fmt"
"reflect"
)
func main() {
slice1 := []int{1, 2, 3}
slice2 := []int{1, 2, 3}
slice3 := []int{1, 2, 3, 4, 5}
fmt.Println(reflect.DeepEqual(slice1, slice2)) // true
fmt.Println(reflect.DeepEqual(slice1, slice3)) // false
}
3. Using Google’s go-cmp package
The go-cmp package was developed to make
comparing the equality of Go values much easier in tests. Essentially, it was
made to be a safer and more comprehensive alternative to reflect.DeepEqual()
.
You can use it to compare slice equality as follows:
go get -u github.com/google/go-cmp/cmp
package main
import (
"fmt"
"github.com/google/go-cmp/cmp"
)
func main() {
slice1 := []int{1, 2, 3}
slice2 := []int{1, 2, 3}
slice3 := []int{1, 2, 3, 4, 5}
fmt.Println(cmp.Equal(slice1, slice2)) // true
fmt.Println(cmp.Equal(slice1, slice3)) // false
}
Final thoughts
And there you have it: three easy ways to compare slice equality in Go. Ensure to check out the slices documentation to learn more about the other useful functions it brings to the language.
Thanks for reading, and happy coding!