How to compare [32]byte with []byte in golang?

Sumit Rathore picture Sumit Rathore · Jan 4, 2015 · Viewed 11.7k times · Source

I want to compare output of sha256.Sum256() which is [32]byte with a []byte.

I am getting an error "mismatched types [32]byte and []byte". I am not able to convert []byte to [32]byte.

Is there a way to do this?

Answer

LinearZoetrope picture LinearZoetrope · Jan 4, 2015

You can trivially convert any array ([size]T) to a slice ([]T) by slicing it:

x := [32]byte{}
slice := x[:] // shorthand for x[0:len(x)]

From there you can compare it to your slice like you would compare any other two slices, e.g.

func Equal(slice1, slice2 []byte) bool {
    if len(slice1) != len(slice2) {
        return false
    }

    for i := range slice1 {
        if slice1[i] != slice2[i] {
            return false
        }
    }

    return true
}

Edit: As Dave mentions in the comments, there's also an Equal method in the bytes package, bytes.Equal(x[:], y[:])