Maps
A map stores values under keys instead of numbered positions — Go's equivalent of a dictionary in Python or an object used as a lookup table in JavaScript.
Creating and reading a map
package main import "fmt" func main() { prices := map[string]float64{ "apple": 0.5, "banana": 0.3, } fmt.Println(prices["apple"]) prices["cherry"] = 2.0 fmt.Println(prices) }
0.5 map[apple:0.5 banana:0.3 cherry:2]
map[string]float64 is a map with string keys and float64 values. Reading a key looks just like indexing a slice; adding a new key is a plain assignment, no separate "insert" method required.
Missing keys and the comma-ok idiom
Reading a key that isn't in the map doesn't panic or error — it just gives you the zero value for the map's value type, which can be genuinely ambiguous. The comma-ok form tells the two cases apart:
package main import "fmt" func main() { stock := map[string]int{"apple": 0, "banana": 12} value, ok := stock["apple"] fmt.Println(value, ok) value, ok = stock["cherry"] fmt.Println(value, ok) }
0 true 0 false
Both lookups print 0 for the value, but ok tells you why: "apple" is genuinely in the map with a stock count of 0, while "cherry" isn't in the map at all and 0 is just the zero value Go handed back. Without checking ok, those two very different situations would look identical.
Deleting a key and iterating
package main import "fmt" func main() { ages := map[string]int{"Priya": 29, "Sam": 34} delete(ages, "Sam") for name, age := range ages { fmt.Println(name, age) } }
Priya 29
delete(ages, "Sam") removes that key entirely, and for name, age := range ages walks every remaining key/value pair. Unlike a slice, a Go map makes no promise about iteration order — running this same code again could print entries in a different order if there were more of them.
var m map[string]int (no make, no literal) is a nil map. Reading from it is safe and just returns zero values, but writing to it — m["x"] = 1 — panics at runtime with "assignment to entry in nil map." Always initialize a map with make(map[K]V) or a map literal before writing to it.