The correct method for hashing an arbitrary object

I am writing a data structure that should hash an arbitrary object. The following function seems to crash if I give a intparameter.

func Hash( obj interface{} ) []byte {
    digest := md5.New()
    if err := binary.Write(digest, binary.LittleEndian, obj); err != nil {
        panic(err)
    }
    return digest.Sum()
}

Calling this parameter does not intresult in:

panic: binary.Write: invalid int type

What is the right way to do this?

+5
source share
2 answers

I found that a good way to do this is to serialize the object using the "gob" package, on the following lines:

var (
    digest = md5.New()
    encoder = gob.NewEncoder(digest)
)

func Hash(obj interface{}) []byte {
    digest.Reset() 
    if err := encoder.Encode(obj); err != nil {
        panic(err)
    }
    return digest.Sum()
}

Edit: this does not work as intended (see below).

+3
source

binary.Write " ". int ; int - "32 64 ". , , int32.

+2

All Articles