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?
To compare two arrays use the comparison operators == or !=
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.
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.
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.
You can form a slice from an array:
func Compare(h1, h2 Sha1Hash) int {
return bytes.Compare(h1[0:20], h2[0:20])
}
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