如何计算地图中按键的哈希值? [英] How does go calculate a hash value for keys in a map?

查看:119
本文介绍了如何计算地图中按键的哈希值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go如何为地图中的键计算散列?它是真正独特的,它是否可用于其他结构?



我想像原始键很容易,像 int 或不可变的字符串,但它对于复合结构来说似乎是不平凡的。

解决方案


  1. 语言规范没有说明,这意味着它随时可以自由更改,或者在实现之间有所不同。


  2. <散列算法在类型和平台之间有所不同。到目前为止:如果CPU支持AES指令,则在x86(32或64位)上运行时使用 aeshash ,这是一个基于AES原语的哈希,否则它使用函数受xxHash和cityhash启发,但与之不同。 32位和64位系统有不同的变体。大多数类型使用它们的内存内容的简单散列,但浮点类型具有代码以确保0和-0散列相等(因为它们相等)并且NaN随机散列(因为两个NaN永远不相等)。由于复杂类型是由浮点构建的,因此它们的哈希由它们两个浮点部分的哈希组成。接口的散列值是存储在接口中的值的散列值,而不是接口头本身。


  3. 所有这些东西都在私有函数中,所以不,你无法在您自己的代码中访问Go的内部哈希值。


How does Go calculate a hash for keys in a map? Is it truly unique and is it available for use in other structures?

I imagine it's easy for primitive keys like int or immutable string but it seems nontrivial for composite structures.

解决方案

  1. The language spec doesn't say, which means that it's free to change at any time, or differ between implementations.

  2. The hash algorithm varies somewhat between types and platforms. As of now: On x86 (32 or 64 bit) if the CPU supports AES instructions, the runtime uses aeshash, a hash built on AES primitives, otherwise it uses a function "inspired by" xxHash and cityhash, but different from either. There are different variants for 32-bit and 64-bit systems. Most types use a simple hash of their memory contents, but floating-point types have code to ensure that 0 and -0 hash equally (since they compare equally) and NaNs hash randomly (since two NaNs are never equal). Since complex types are built from floats, their hashes are composed from the hashes of their two floating-point parts. And an interface's hash is the hash of the value stored in the interface, and not the interface header itself.

  3. All of this stuff is in private functions, so no, you can't access Go's internal hash for a value in your own code.

这篇关于如何计算地图中按键的哈希值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆