Sobes.tech
Middle

How does a hash table work?

sobes.tech AI

Answer from AI

A hash table is a data structure that provides fast access to elements by key. It works as follows:

  1. The key is transformed into an array index using a hash function.
  2. At this index, a value or a list of values (in case of collisions) is stored.
  3. In case of collisions (when different keys produce the same index), a collision resolution method is used, such as chaining (linked list) or open addressing.

In Go, the built-in map type implements a hash table, allowing quick retrieval, addition, and deletion of elements by key.

Example of using a map in Go:

package main
import "fmt"

func main() {
    m := make(map[string]int)
    m["apple"] = 5
    m["banana"] = 3

    fmt.Println(m["apple"]) // 5

    // Checking if a key exists
    val, ok := m["banana"]
    if ok {
        fmt.Println("banana exists, value:", val)
    }
}