Sobes.tech
Senior

How are maps structured in Go?

sobes.tech AI

Answer from AI

In Go, a map is a built-in data type that implements an associative array or dictionary, where keys are mapped to values.

Main features:

  • Declaration: map[keyType]valueType.
  • Initialization: using the make function or a literal.
  • Access: reading and writing by key.
  • No order: elements in a map are unordered.
  • Concurrency safety: map is not thread-safe; synchronization is required for concurrent access.

Example:

package main
import "fmt"

func main() {
    // Create a map with string keys and int values
    ages := make(map[string]int)

    // Add elements
    ages["Alice"] = 30
    ages["Bob"] = 25

    // Read an element
    fmt.Println("Age of Alice:", ages["Alice"])

    // Check for key existence
    age, ok := ages["Charlie"]
    if !ok {
        fmt.Println("Key Charlie not found")
    } else {
        fmt.Println("Age of Charlie:", age)
    }
}

Thus, a map in Go is a convenient and efficient way to store key-value pairs with quick access.