Junior — Middle
Can you explain the principle of hashing in the implementation of a map (Map)?
sobes.tech AI
Answer from AI
In Go, a map is implemented as a hash table where keys are transformed into hash values using a hash function. The principle of hashing in a map is as follows:
- A hash code is computed for a given key — a numerical value that depends on the content of the key.
- The hash code is used to determine the index in the array of buckets where the value is stored.
- If multiple elements are in a bucket (collision), a search is performed through a chain or another collision resolution mechanism.
This allows for quick finding, adding, and removing elements by key with an amortized complexity of about O(1).
Example of using a map in Go:
m := make(map[string]int)
m["apple"] = 5
value := m["apple"] // value == 5
In this example, the string "apple" is hashed, and the value 5 is stored in the corresponding bucket.