Go Maps

What is a Map?

A map is an unordered collection of key-value pairs. Keys must be unique and comparable.

Maps are equivalent to dictionaries in Python or objects in Java

var m map[string]int
m = make(map[string]int)

You can also initialize a map with values:

m := map[string]int{
    "apples":  5,
    "bananas": 10,
}

Access and Modify

m["grapes"] = 7
fmt.Println(m["apples"]) // prints 5

If the key doesn’t exist, Go returns the zero value for the type (e.g., 0 for int).

Check Key Existence

val, ok := m["kiwi"]
if ok {
    fmt.Println("Kiwi found:", val)
} else {
    fmt.Println("Kiwi not in map")
}

This is idiomatic Go — the second value of the map access tells you if the key exists.

Deleting Keys

delete(m, "bananas")

This removes the key if it exists; otherwise it does nothing.

Iterating Over a Map

for k, v := range m {
    fmt.Printf("%s: %d\n", k, v)
}

Note: Map iteration order is not guaranteed.

Maps of Structs

Maps can store structs as values:

type Product struct {
    Price int
}

inventory := map[string]Product{
    "pen": {Price: 2},
    "notebook": {Price: 5},
}

Nested Maps

data := map[string]map[string]int{
    "alice": {"math": 95, "science": 88},
    "bob":   {"math": 72, "science": 91},
}

Useful for representing JSON-like hierarchical data.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic