Senior
Mis on map Go-s, kuidas see sees toimib, mis on kokkupõrge ja kuidas sellega võidelda?
sobes.tech AI
Vastus AI-lt
In Go, map is an built-in data type for storing key-value pairs with quick access. Inside map, a hash table mechanism is implemented.
Internal structure:
- The key is hashed into an integer value.
- The hash determines the index of the bucket where pairs are stored.
- Each bucket contains multiple key-value pairs.
Collision: a situation where different keys have the same hash and fall into the same bucket. To handle this, Go uses:
- storing multiple pairs in one bucket.
- when there are many collisions, a rehash is performed by increasing the number of buckets.
This allows maintaining quick access to elements even in case of collisions.
Example of using map:
m := make(map[string]int)
m["apple"] = 5
fmt.Println(m["apple"]) // 5
Thus, map in Go is an efficient structure for associative arrays with internal optimization to minimize the impact of collisions.