Understand the contract

A map associates keys with values. Use make or a map literal before inserting entries. Reading a missing key returns the value type’s zero value, so use the two-result lookup when absence has a different meaning from a stored zero. The second result reports whether the key exists.

Keys must be comparable. Strings and integers work as keys; slices do not. delete removes an entry and does nothing when the key is absent. len counts entries. Map assignment shares the same map data, so passing a map to a function can allow that function to update its entries.

Work through the example

The example stores an existing key with value zero. Its lookup prints 0 true, whereas an absent key prints 0 false. This is useful for counts, configuration and caches where zero can be a valid result. Make the presence decision explicit before using a fallback value.

package main

import "fmt"

func main() {
    counts := map[string]int{"go": 0}
    value, ok := counts["go"]
    fmt.Println(value, ok)
    value, ok = counts["rust"]
    fmt.Println(value, ok)
}

Watch this boundary

A nil map supports reads, len and delete, but inserting into it panics. Iteration order is unspecified, and plain maps do not support concurrent reads and writes without synchronization. Later lessons cover sorting keys for deterministic output and protecting shared state with a mutex.

Practice with a changed input

Add a second key, delete it and compare the lookup results. Declare a nil map and check its length, then initialize it before inserting a value.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services