Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does go calculate a hash value for keys in a map?

Tags:

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.

like image 421
Kevin Deenanauth Avatar asked Jun 04 '16 01:06

Kevin Deenanauth


People also ask

How are hash values calculated?

Hashing is simply passing some data through a formula that produces a result, called a hash. That hash is usually a string of characters and the hashes generated by a formula are always the same length, regardless of how much data you feed into it. For example, the MD5 formula always produces 32 character-long hashes.

Is a go map a hash table?

One of the most useful data structures in computer science is the hash table. Many hash table implementations exist with varying properties, but in general they offer fast lookups, adds, and deletes. Go provides a built-in map type that implements a hash table.

What is a hash function in maps?

A hash function maps keys to small integers (buckets). An ideal hash function maps the keys to the integers in a random-like manner, so that bucket values are evenly distributed even if there are regularities in the input data. This process can be divided into two steps: Map the key to an integer.

What is my hash value?

A hash value is a numeric value of a fixed length that uniquely identifies data. Hash values represent large amounts of data as much smaller numeric values, so they are used with digital signatures. You can sign a hash value more efficiently than signing the larger value.


1 Answers

  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.
like image 180
hobbs Avatar answered Oct 12 '22 23:10

hobbs