Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing arrays in Go language

Tags:

arrays

go

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?

like image 223
angry_gopher Avatar asked Sep 01 '13 17:09

angry_gopher


People also ask

How do you compare two slices in go?

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.

How do you compare bytes in go?

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.


2 Answers

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.

like image 181
zzzz Avatar answered Sep 28 '22 04:09

zzzz


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

like image 27
Intermernet Avatar answered Sep 28 '22 05:09

Intermernet