Go Reference ยท Built-in Types
Go maps
Reference for Go maps: creating, lookup with the comma-ok idiom, delete, nil maps, key requirements, random iteration order and concurrency rules.
A map is an unordered collection of key-value pairs, implemented as a hash table. The type map[K]V maps keys of type K to values of type V. Lookups, inserts and deletes take constant time on average.
Maps are reference-like: assigning a map or passing it to a function shares the same underlying table. The zero value is a nil map, which you can read from but not write to.
ages := map[string]int{"Ada": 36, "Linus": 54} ages["Grace"] = 85
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
var m map[K]V // nil map m := map[K]V{k1: v1, k2: v2} // literal m := make(map[K]V, hint) // empty, with a size hint v := m[k] // zero value if missing v, ok := m[k] // ok reports presence m[k] = v // insert or overwrite delete(m, k) // remove, no-op if absent n := len(m)
| Part | Description |
|---|---|
K |
Any comparable type: numbers, strings, booleans, pointers, channels, arrays and structs of comparable types, interfaces. Not slices, maps or functions. |
V |
Any type. |
hint |
Optional initial capacity; affects performance only. |
Edge cases: writing to a nil map panics; reading from one is fine. A key containing an interface that holds an unhashable dynamic value (such as a slice) panics at run time. NaN keys never match anything, even themselves.
Usage notes
- Iteration order is unspecified and deliberately randomized. Sort the keys (or use
slices.Sorted(maps.Keys(m))since Go 1.23) when output must be stable. - Map values are not addressable.
m[k].field = 1does not compile for struct values; store pointers or copy, modify and store back. - Modifying while ranging is allowed: deleting entries not yet reached means they will not be produced, and entries added during iteration may or may not be produced.
- Concurrent access is not safe. A write concurrent with any other access can crash the program with a fatal error. Guard with a
sync.Mutex, or usesync.Mapfor specific patterns. - Memory is not returned when you delete entries; a map that once held millions keeps its buckets. Create a new map to shrink. Since Go 1.21
clear(m)removes all entries. - A set is usually
map[T]struct{}(zero bytes per value) ormap[T]bool(more convenient lookups). - The
mapspackage (Go 1.21) providesClone,Copy,Equal,DeleteFunc; Go 1.23 added iterator helpersKeys,Values,All,Collect.