Maps
Creating a map
Section titled “Creating a map”A map is a hash table that maps keys of type K to values of type V. Create one with make or a composite literal:
// make — preferred when you add entries incrementallyscores := make(map[string]int)
// composite literal — preferred when entries are known upfrontscores := map[string]int{ "Alice": 95, "Bob": 87,}The key type must be comparable (supports ==). Valid key types include string, int, all numeric types, booleans, pointers, and structs whose fields are all comparable. Slices, maps, and functions cannot be used as keys.
Set, get, delete
Section titled “Set, get, delete”scores["Charlie"] = 72 // setfmt.Println(scores["Alice"]) // get → 95delete(scores, "Bob") // delete (no-op if key absent)Missing-key zero value
Section titled “Missing-key zero value”Reading a key that does not exist never panics — it returns the zero value for the value type:
fmt.Println(scores["Dave"]) // 0 — not a panicThis is convenient but can hide bugs: you cannot tell whether a key maps to 0 or was never set. Use the comma-ok idiom to distinguish.
The comma-ok idiom
Section titled “The comma-ok idiom”A two-result map lookup returns the value and a boolean indicating whether the key was present:
v, ok := scores["Dave"]if !ok { fmt.Println("Dave not found")}Maps are reference types
Section titled “Maps are reference types”Assigning a map copies the header, not the data. Both variables point to the same underlying hash table:
a := map[string]int{"x": 1}b := ab["x"] = 99fmt.Println(a["x"]) // 99 — a and b share the same mapIteration order is randomized
Section titled “Iteration order is randomized”Go deliberately randomizes map iteration order on every run to prevent code from depending on an undefined order. To print map entries deterministically, sort the keys first:
import "sort"
keys := make([]string, 0, len(scores))for k := range scores { keys = append(keys, k)}sort.Strings(keys)for _, k := range keys { fmt.Printf("%s: %d\n", k, scores[k])}package main
import ( "fmt" "sort")
func main() { // make a map and add entries scores := make(map[string]int) scores["Alice"] = 95 scores["Bob"] = 87 scores["Charlie"] = 72
// Comma-ok idiom v, ok := scores["Bob"] fmt.Println(v, ok) // 87 true
v2, ok2 := scores["Dave"] fmt.Println(v2, ok2) // 0 false
// Delete an entry delete(scores, "Charlie")
// Sort keys for deterministic output keys := make([]string, 0, len(scores)) for k := range scores { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { fmt.Printf("%s: %d\n", k, scores[k]) }}Loading Go runtime (first run only, ~8 MB)…