Thuta Learning
IntermediateProgrammingbeginner

Maps

Relax. We'll talk through this in plain words — no textbook voice.

Map is a data structure that stores key-value pairs. It's useful anywhere you want to look up a value by its key — like a username to a score, a product ID to a price, or a setting name to its value.

go
package main

import "fmt"

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

    scores["Mya"] = 95

    score, exists := scores["Su"]
    fmt.Println("Su score:", score)
    fmt.Println("Exists:", exists)
    fmt.Println(scores)
}

scores["Su"] uses the key to get its value. The second return value, exists, tells you whether the key actually exists.

You should see
Su score: 85 Exists: true map[Aung:90 Mya:95 Su:85]

Info

Map output order isn't guaranteed to stay the same. If order matters, put the keys into a slice and sort it.

Easy traps

  • Looking up a value for a key that doesn't exist can return the zero value. That's why it's a good idea to use the value, ok := map[key] pattern.
Maps | Thuta Learning