Sobes.tech
Junior

What functions does the map data structure perform in Go?

sobes.tech AI

Answer from AI

map is an unordered collection of key-value pairs.

Main functions:

  • Data storage: Allows associating values with unique keys.
  • Fast access: Provides efficient access to values by their keys (average O(1)).
  • Element removal: Easily removes key-value pairs.
  • Existence check: Checks if a key exists in the map.
  • Iteration: Allows iterating over all key-value pairs (iteration order is not guaranteed).

Example of usage:

// Declaration and initialization of a map
students := map[string]int{
    "Alice": 25,
    "Bob":   30,
}

// Adding an element
students["Charlie"] = 22

// Accessing an element
ageOfAlice := students["Alice"]

// Checking existence and retrieving value
if age, ok := students["Bob"]; ok {
    // Bob exists
}

// Removing an element
delete(students, "Charlie")

// Iterating over the map
for name, age := range students {
    // ...
}