A map is Go's built-in hash table: unordered key-value pairs with fast average-case lookup, insert, and delete.
var m map[string]int declares a nil map. Reading from a nil map returns the zero value, but writing to one panics.
var m map[string]intmake allocates a usable, empty map. This is the standard way to get a map you intend to write into.
m := make(map[string]int)A map literal declares and initializes in one step, with each key: value pair separated by commas.
m := map[string]int{
"a": 1,
"b": 2,
}Indexing a map returns two values: the value, and whether the key was actually present. This comma-ok idiom is the only way to distinguish a stored zero value from a missing key.
v, ok := m["a"]
// v = 1, ok = true
v, ok = m["z"]
// v = 0, ok = falsedelete removes a key from the map. Deleting a key that doesn't exist is a no-op, not an error.
delete(m, "b")Printing a map shows its remaining keys in sorted order courtesy of fmt, though iteration with for range visits keys in randomized order at runtime.
$ go run maps.go
map[a:1]