doukan5332 2016-04-19 19:39
浏览 31

如何创建自定义哈希码以确定数据是否已突变

Say I have a struct type that has int64 and bools, along with embedded types that have more int64 and bool type fields.

type T1 struct {
   f1 int64
   f2 int64
   f3 bool
   T2 T2
}

type T2 struct {
   f4 int64
   f5 int64
   f6 bool
}

Now using all the structs fields/properties, I want to generate a hashcode.

The aim of this is so I can determine if the contents of the instance has changed but comparing the before/after hashcode value.

So if T1 instance has changed i.e. any of its own properties Then the value of the hash should be different.

  • 写回答

1条回答 默认 最新

  • dongshangan2074 2016-04-20 11:56
    关注

    You can use something like:

    func (t *T1) Hash() uint64 {
        hb := make([]byte, 8+8+1+8+8+1)
        binary.BigEndian.PutUint64(hb, uint64(t.f1))
        binary.BigEndian.PutUint64(hb[8:], uint64(t.f2))
        if t.f3 {
            hb[16] = 1
        }
        binary.BigEndian.PutUint64(hb[17:], uint64(t.T2.f4))
        binary.BigEndian.PutUint64(hb[25:], uint64(t.T2.f5))
        if t.T2.f6 {
            hb[33] = 1
        }
        f := fnv.New64a()
        f.Write(hb)
        return f.Sum64()
    }
    

    <kbd>playground</kbd>

    Although if you are using it as a map key, it's better to just directly use the struct as the key and let go handle it.

    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集