Go Maps
External
Internal
Overview
Maps and Pass-by-Value
Pointers to Maps
nil and Empty Map
nil Map
Empty Map
Declaration and Initialization
Initialization with make()
Initialization with a Composite Literal
Composite literals can be used for map initialization.
Long variable declaration and initialization with type inference:
var mm = map[string]int{"A": 1, "B": 2}
mm := map[string]int{"A": 1, "B": 2}
Operators
Indexing Operator []
Values stored in a map can be referenced with the indexing operator []
, using the [key]
syntax.
The indexing operator returns two values: the value associated with the key, or zero-value for the type if the key does not exist in map, and a boolean that says whether the key exists or not in the map.
The second returned value can be syntactically omitted, but given the fact that the indexing operator returns the zero value for the type and not nil
on missing keys, it is impossible to say without it whether the key is missing, or a zero-value was associated with the key.
mm := map[string]int{"A": 1, "B": 2}
v, ok := mm["A"]
fmt.Printf("%d, %t\n", v, ok) // will display 1, true
If the key does not exist in map, the retuned value is not nil
, but the zero value for the type.
The indexing operator can be used to change the value associated with a key, or to add a new key/value pair:
mm["A"] = 7
mm["C"] = 9
Map Functions
delete()
len()
len()
returns the number of keys. Note that the built-in cap()
function does not work on maps. Unlike slices, maps do not have the concept of capacity.