Comparing arrays in Go language

To compare two arrays use the comparison operators == or !=. Quoting from the link:

Array values are comparable if values of the array element type are comparable. Two array values are equal if their corresponding elements are equal.

As a 2D (or ND) array fits the above requirement, you can compare it in the same way.

The question "How deep is that comparison?" doesn't make sense for arrays.


For "Deep" comparison, you can use reflect.DeepEqual.

DeepEqual tests for deep equality. It uses normal == equality where possible but will scan elements of arrays, slices, maps, and fields of structs. In maps, keys are compared with == but elements use deep equality. DeepEqual correctly handles recursive types. Functions are equal only if they are both nil. An empty slice is not equal to a nil slice.

Example:

package main

import (
    "bytes"
    "fmt"
    "reflect"
)

func main() {
    a := []byte{}    // empty slice
    b := []byte(nil) // nil slice
    fmt.Printf("%t\n%t", bytes.Equal(a, b), reflect.DeepEqual(a, b))
}

Returns:

true
false

The caveat is that it's slow.

Playground

Tags:

Arrays

Go