How can I correctly compare two arrays in Go?
For instance, how can I compare two dimensional arrays with int entries, or any other types?
How deep is that comparison?
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.
If you have 2 int
slices/arrays try this:
func IntArrayEquals(a []int, b []int) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
NOTE: this is for 1D arrays, but you can rewrite it for 2D.
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
%t", bytes.Equal(a, b), reflect.DeepEqual(a, b))
}
Returns:
true
false
The caveat is that it's slow.