Skip to content

Go Maps

Maps are Go's built-in associative data type (sometimes called hashes or dicts in other languages). They store data in key-value pairs.

1. Basic Usage

To create an empty map, use the built-in make function.

package main
import "fmt"

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

    // 2. Set key/value pairs
    m["key1"] = 7
    m["key2"] = 13
    fmt.Println("map:", m)

    // 3. Get a value
    v1 := m["key1"]
    fmt.Println("v1: ", v1)

    // 4. Delete a key
    delete(m, "key2")
    fmt.Println("map:", m)
}

2. Map Literals

You can declare and initialize a new map on the same line.

n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)

3. Checking if a Key Exists

When you read from a map, it returns two values: the value and a boolean indicating if the key was actually present.

1
2
3
4
5
6
v, ok := m["key2"]
if ok {
    fmt.Println("Key exists, value:", v)
} else {
    fmt.Println("Key not found")
}

Important Notes

  1. Zero Value: If a key doesn't exist, Go returns the zero value for the value type (e.g., 0 for an int map).
  2. Unordered: Maps are inherently unordered. If you iterate over a map multiple times, the order of keys is not guaranteed to be the same.
  3. Reference Type: Like slices, maps are passed by reference.