适当的方法来哈希任意对象

huangapple go评论170阅读模式
英文:

Proper method to hash an arbitrary object

问题

我正在编写一个需要对任意对象进行哈希的数据结构。如果我将一个int作为参数传递给以下函数,它似乎会失败。

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

int上调用此函数会导致:

> panic: binary.Write: invalid type int

正确的做法是什么?

英文:

I am writing a data structure that needs to hash an arbitrary object. The following function seems to fail if I give an int is the parameter.

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 on an int results in:

> panic: binary.Write: invalid type int

What is the right way to do this?

答案1

得分: 3

我发现一个很好的方法是使用"gob"包对对象进行序列化,代码如下:

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()
}

编辑:这个方法并不按预期工作(见下文)。

英文:

I found that a good way to do this is to serialize the object using the "gob" package, along 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).

答案2

得分: 2

binary.Write写入"一个固定大小的值或指向固定大小值的指针"。类型int不是一个固定大小的值;int是"32位或64位"。使用一个固定大小的值,比如int32。

英文:

binary.Write writes "a fixed-size value or a pointer to a fixed-size value." Type int is not a fixed size value; int is "either 32 or 64 bits." Use a fixed-size value like int32.

huangapple
  • 本文由 发表于 2011年4月23日 07:32:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/5761014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定