Go 1.21 and above
The function is now in the standard library: slices.Equal
.
Go 1.18 to 1.20
You cannot use ==
or !=
with slices but if you can use them with the elements then Go 1.18 has a new function in the golang.org/x/exp
package to easily compare two slices, slices.Equal
:
Equal reports whether two slices are equal: the same length and all elements equal. If the lengths are different, Equal returns false. Otherwise, the elements are compared in increasing index order, and the comparison stops at the first unequal pair. Floating point NaNs are not considered equal.
The slices
package import path is golang.org/x/exp/slices. Code inside exp
package is experimental, not yet stable. It will be moved into the standard library in Go 1.19 eventually.
Nevertheless you can use it as soon as Go 1.18 (playground)
sliceA := []int{1, 2}
sliceB := []int{1, 2}
equal := slices.Equal(sliceA, sliceB)
fmt.Println(equal) // true
type data struct {
num float64
label string
}
sliceC := []data{{10.99, "toy"}, {500.49, "phone"}}
sliceD := []data{{10.99, "toy"}, {200.0, "phone"}}
equal = slices.Equal(sliceC, sliceD)
fmt.Println(equal) // true
If the elements of the slice don't allow ==
and !=
, you can use slices.EqualFunc
and define whatever comparator function makes sense for the element type.