Sobes.tech
Senior

How is Map in Go organized under the hood?

sobes.tech AI

Answer from AI

In Go, a map is implemented as a hash table with open addressing and chaining to resolve collisions. Under the hood, it uses an array of buckets, each containing multiple keys and values, as well as pointers for collision handling.

Main implementation points:

  • The hash function computes the bucket index.
  • Each bucket contains several key-value pairs (usually 8).
  • In case of collisions, elements can be stored in neighboring buckets or in overflow lists.
  • When the table is filled above a certain threshold, rehashing occurs with an increased size.
  • To optimize, an incremental rehashing algorithm is used to avoid blocking the map for a long time.

Example of using a map in Go:

m := make(map[string]int)
m["apple"] = 5
fmt.Println(m["apple"]) // 5

Thus, a map in Go is an efficient hash table with optimizations for fast access and minimal allocations.