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 check if two slices are equal, write a custom function that compares their lengths and corresponding elements in a loop. You can also use the reflect. DeepEqual() function that compares two values recursively, which means it traverses and checks the equality of the corresponding data values at each level.
Golang bytes Compare() is an inbuilt function that returns an integer comparing two-byte slices lexicographically. The final result will be 0 if a==b, -1 if the a < b, and +1 if a > b. A nil argument is equivalent to the empty slice.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With