0
0
GoConceptBeginner · 3 min read

What is map in Go: Explanation and Examples

In Go, a map is a built-in data type that stores key-value pairs, similar to a dictionary in other languages. It allows you to quickly look up a value by its unique key.
⚙️

How It Works

A map in Go works like a real-world dictionary where you look up a word (the key) to find its meaning (the value). Instead of searching through a list, the map lets you jump directly to the value using the key, making data retrieval very fast.

Internally, Go organizes the map so it can quickly find the value for any given key without checking every item. You can add, update, or delete key-value pairs easily. Keys must be unique and of a type that can be compared, like strings or integers.

💻

Example

This example shows how to create a map, add items, and get a value by its key.

go
package main

import "fmt"

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

    // Add key-value pairs
    ages["Alice"] = 30
    ages["Bob"] = 25

    // Retrieve and print a value by key
    fmt.Println("Alice's age is", ages["Alice"])

    // Check if a key exists
    age, ok := ages["Charlie"]
    if ok {
        fmt.Println("Charlie's age is", age)
    } else {
        fmt.Println("Charlie is not in the map")
    }
}
Output
Alice's age is 30 Charlie is not in the map
🎯

When to Use

Use a map in Go when you need to associate unique keys with values for fast lookup. For example, storing user IDs and their names, counting word frequencies in text, or caching results for quick access.

Maps are ideal when you want to quickly find, add, or remove data without searching through a list. However, if order matters, maps do not keep items sorted.

Key Points

  • Maps store key-value pairs for fast access.
  • Keys must be unique and comparable types.
  • Maps are dynamic and can grow as needed.
  • Maps do not maintain order of elements.
  • Use make to create a map before adding items.

Key Takeaways

A map in Go stores unique keys with associated values for fast lookup.
Use make(map[keyType]valueType) to create a map before adding data.
Maps are great for quick searches but do not keep items in order.
Keys must be types that can be compared, like strings or integers.
Maps let you add, update, and delete key-value pairs easily.