Go Lesson 16 – Maps | Dataplexa

Maps in Go

Maps in Go are used to store data in key–value pairs. They are ideal when you want to quickly look up a value using a unique key.

Unlike slices, which use numeric indexes, maps allow you to use meaningful keys such as names, IDs, or codes.


What Is a Map?

A map is a built-in data type in Go that associates keys with values. Each key must be unique, and each key points to exactly one value.

Maps are commonly used to represent dictionaries, configurations, lookup tables, and records.


Declaring a Map

You can declare a map by specifying the key type and value type.

package main

import "fmt"

func main() {
    var prices map[string]int
    fmt.Println(prices)
}

This declares a map where the key is a string and the value is an integer. At this stage, the map is nil and cannot store values yet.


Creating a Map Using make()

To use a map, it must be initialized using the make() function.

package main

import "fmt"

func main() {
    prices := make(map[string]int)
    prices["Laptop"] = 75000
    prices["Phone"] = 45000

    fmt.Println(prices)
}

Now the map can store and retrieve values using keys.


Creating a Map Using Literals

Maps can also be created using a literal syntax. This is the most common and readable approach.

package main

import "fmt"

func main() {
    scores := map[string]int{
        "Alice": 85,
        "Bob":   90,
        "Carol": 78,
    }

    fmt.Println(scores)
}

Here, student names are used as keys and their scores as values.


Accessing Values from a Map

You can retrieve a value by using its key.

package main

import "fmt"

func main() {
    scores := map[string]int{
        "Alice": 85,
        "Bob":   90,
    }

    fmt.Println("Alice Score:", scores["Alice"])
}

If the key exists, Go returns the associated value.


Checking If a Key Exists

Go provides a special syntax to check whether a key exists in a map.

package main

import "fmt"

func main() {
    stock := map[string]int{
        "Apples":  50,
        "Bananas": 30,
    }

    value, exists := stock["Apples"]

    if exists {
        fmt.Println("Apples available:", value)
    } else {
        fmt.Println("Apples not available")
    }
}

This prevents errors when accessing keys that may not exist.


Updating Map Values

You can update a value by assigning a new value to an existing key.

package main

import "fmt"

func main() {
    inventory := map[string]int{
        "Pens":  20,
        "Books": 15,
    }

    inventory["Pens"] = 25
    fmt.Println(inventory)
}

The value for the key Pens is updated from 20 to 25.


Deleting Elements from a Map

The built-in delete() function removes a key–value pair from a map.

package main

import "fmt"

func main() {
    users := map[string]string{
        "admin": "active",
        "guest": "inactive",
    }

    delete(users, "guest")
    fmt.Println(users)
}

After deletion, the key no longer exists in the map.


Iterating Over a Map

Maps can be iterated using a for range loop.

package main

import "fmt"

func main() {
    salaries := map[string]int{
        "John":  50000,
        "Sara":  62000,
        "Mike":  58000,
    }

    for name, salary := range salaries {
        fmt.Println(name, "earns", salary)
    }
}

The order of iteration is not guaranteed in maps.


Real-World Example: Product Price Lookup

Maps are ideal for fast lookups, such as retrieving product prices.

package main

import "fmt"

func main() {
    products := map[string]int{
        "Keyboard": 1500,
        "Mouse":    800,
        "Monitor":  12000,
    }

    item := "Monitor"
    fmt.Println(item, "Price:", products[item])
}

This allows instant access to prices using product names.


When to Use Maps

  • Fast lookups using keys
  • Storing configuration settings
  • Representing real-world entities
  • Counting occurrences or frequencies

What’s Next?

In the next lesson, you will learn about the range keyword in Go, which is used to iterate efficiently over slices, arrays, and maps.