Sobes.tech
Junior — Middle

Kas saaksite selgitada hashimise tööpõhimõtet kaardi (Map) rakendamisel?

sobes.tech AI

Vastus AI-lt

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:

  1. For a given key, a hash code is calculated — a numerical value depending on the content of the key.
  2. The hash code is used to determine the index in the array of buckets (bins) where the value is stored.
  3. If there are multiple elements in a bucket (collision), a search is performed via chaining or another collision resolution mechanism.

This allows for quick finding, adding, and deleting of 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.