A Go Map Returns the Zero Value for a Missing Key, So Check with comma ok

In progress

Go's built-in map (a hash table, like a dict or hash elsewhere) never raises an error for a missing key: it returns the value type's zero value ("", 0, false, nil). That's convenient for counters and ambiguous for everything else: a missing key and a key stored with the zero value look the same. The two-value form, v, ok := m[k], tells them apart.

Basics

technologies := make(map[string]string)
technologies["database"] = "Postgres"
technologies["frontend"] = "HTMX"

db := technologies["database"]          // "Postgres"
cache := technologies["cache"]          // "": missing, but no error

if v, ok := technologies["cache"]; ok {
    fmt.Println("cache:", v)
} else {
    fmt.Println("no cache configured")
}

delete(technologies, "frontend")

The zero value is handy when it means something: counts[word]++ works without initialising each key.

Three Rules That Cause Bugs

What Can Be a Key

Any comparable type: strings, numbers, booleans, pointers, and structs or arrays made of those. Slices, maps and functions can't be keys. Values can be anything, structs and slices included.

References

Review cards

Flashcard Why use `v, ok := m[k]` instead of `m[k]`?

A missing key returns the zero value without error, so m[k] can't tell a missing key from one stored with the zero value. ok is false only when the key is missing.

Flashcard What happens when you write to a map declared as `var m map[string]int`?

It's a nil map: reads return zero values, but m["a"] = 1 panics. Create maps with make or a literal.