Introduction to Maps

Maps are Go’s built-in associative data type, similar to dictionaries in Python or objects in JavaScript. They provide efficient $O(1)$ lookups for key-value pairs.

Declaration

You can create a map using the make() function or a map literal.

// Using make
ages := make(map[string]int)
ages["Alice"] = 30

// Using a literal
scores := map[string]int{
    "Alice": 100,
    "Bob":   85,
}

Key Properties

  • Zero Value: The zero value of a map is nil. A nil map has no keys and cannot be added to.
  • Dynamic Size: Maps grow automatically as you add elements.
  • len(): Returns the number of key/value pairs in the map.
fmt.Println(len(scores)) // 2