How to Check the Equality of two Slices in Go

Created
Modified

Using bytes.Equal Function

Equal reports whether a and b are the same length and contain the same bytes. A nil argument is equivalent to an empty slice.

For example,

package main

import (
  "bytes"
  "fmt"
)

func main() {
  a := []byte{1, 2, 3}
  b := []byte{1, 2, 3}

  fmt.Println(bytes.Equal(a, b))
}
true

Using reflect.DeepEqual Function

DeepEqual reports whether x and y are “deeply equal,” defined as follows.

See the following example:

package main

import (
  "fmt"
  "reflect"
)

func main() {
  a := []int{1, 2, 3}
  b := []int{1, 2, 3}
  c := []int{1, 3, 2}

  fmt.Println(reflect.DeepEqual(a, b))
  // a[1] != c[1]
  fmt.Println(reflect.DeepEqual(a, c))
}
true
false

Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal.

Using slices.Equal Function

Starting with Go 1.18, we can compare two slices easily using slices.Equal.

The slices package import path is golang.org/x/exp/slices. Code inside exp package is experimental, not yet stable. It could be moved to the standard library in Go 1.19.

// version 1.18+
package main

import (
  "fmt"

  "golang.org/x/exp/slices"
)

func main() {
  a := []int{1, 2, 3}
  b := []int{1, 2, 3}

  fmt.Println(slices.Equal(a, b))
}
true

Related Tags

#check# #slice#