Maps and structs
Go's two everyday aggregate types.
A map is a hash table keyed by a comparable type; a struct groups named fields and can carry methods β together they model most of your data.
Maps
A map in Go is a built-in hash table written map[K]V. The key type K must be comparable (strings, numbers, booleans, structs of comparable fields), and V is any type. Create one with a literal β map[string]int{"a": 1} β or with make(map[string]int). Indexing a missing key returns the zero value for V, not an error, so reads never panic.
To tell "present but zero" from "absent", use the comma-ok form: v, ok := m[key]. ok is true only when the key exists.
Structs
A struct is a fixed set of named fields, declared with type Point struct { X, Y int }. You build one with a literal β Point{X: 1, Y: 2} β and read fields with the dot operator: p.X. Structs are value types: assigning or passing one copies every field.
Methods
You attach behaviour to a struct by declaring a method β a function with a receiver before its name. A value receiver (p Point) works on a copy; a pointer receiver (p *Point) can mutate the original. Methods are how Go models objects without classes.
Iterating in order
Ranging over a map visits keys in a deliberately randomised order, so output is non-deterministic. When you need a stable order, collect the keys into a slice, sort them, then range the slice and look each key up.
Try it 5 examples
Map literal and comma-ok lookup
GointroReading the absent key "carol" yields 0 (int's zero value) with no panic, while comma-ok returns found: true for "bob" and false for "carol" β that boolean is the only reliable way to tell a stored zero from a missing key.