Sobes.tech
Middle+

Hash was calculated, bucket found, new value inserted. What happens when a new value with the same hash (collision) arrives?

sobes.tech AI

Answer from AI

In Go, when working with a map, a hash collision (different keys having the same hash) is handled using chaining within a bucket.

The algorithm roughly works as follows:

  1. The hash of the key is computed.
  2. The bucket (bin) in the array of buckets is determined by the hash.
  3. Each bucket stores a list of key-value pairs.
  4. When inserting a new value with the same hash, Go iterates through the elements in the bucket and compares keys using an equality function.
  5. If the key matches, the value is updated.
  6. If the key is new, the element is added to the list in the bucket.

Thus, collisions are handled by storing multiple elements in one bucket and sequentially comparing keys.

Example:

m := make(map[string]int)
m["key1"] = 1
m["key2"] = 2 // key2 may have the same hash as key1
// When inserting key2, Go checks the bucket and adds or updates the value
Hash was calculated, bucket found, new value… - sobes.tech