Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare arrays golang

Tags:

arrays

compare

go

I have defined my own type in Go:

type Sha1Hash [20]byte

I would like to sort two of these hashes, h1 and h2:

func Compare(h1, h2 Sha1Hash) int {

    h1 >= h2 // doens't work, arrays only have == and !=
    bytes.Compare(h1,h2) //doesn't work, Compare only works on slices

}

How can I compare my arrays?

like image 773
Peter Smit Avatar asked Dec 16 '14 17:12

Peter Smit


People also ask

How do I compare string arrays in Golang?

To compare two arrays use the comparison operators == or !=

How do I compare byte arrays in go?

In the Go slice, you are allowed to compare two slices of the byte type with each other using Compare() function. This function returns an integer value which represents that these slices are equal or not and the values are: If the result is 0, then slice_1 == slice_2.

How can I check if two slices are equal?

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.

Is it possible to check if the slices are equal with == operator or not?

Slices in Go are not comparable, so a simple equality comparison a == b is not possible. 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.


1 Answers

You can form a slice from an array:

func Compare(h1, h2 Sha1Hash) int {
    return bytes.Compare(h1[0:20], h2[0:20]) 
}
like image 187
Frédéric Donckels Avatar answered Sep 29 '22 07:09

Frédéric Donckels