Maps are mapping keys to values. The key is then used to “unlock” the data, e. g. to give us access or the ability to overwrite the value.
When creating a map, first the data type of the key is defined. In the following code example, we set the key to be a string. Following is the type of the actual value.
”CEO” is the key, while the Person-instance is the value.
This can be rewritten to literals:
Here, we turned from declaration to declaration and initialization. Actually, providing the Person-type here in the initialization is optional: “If the top-level type is just a type name, you can omit it from the elements of the literal.”
Mutating maps
Insert or update an element in map m
:
m[key] = elem
Retrieve an element:
elem = m[key]
Delete an element:
delete(m, key)
Test that a key is present with a two-value assignment:
elem, ok = m[key]
If key
is in m
, ok
is true
. If not, ok
is false
.
If key
is not in the map, then elem
is the zero value for the map’s element type.
Note: If elem
or ok
have not yet been declared you could use a short declaration form:
elem, ok := m[key]
Creating maps with make
To understand what make
does, check this make and new
When creating a map with make
one can’t initialize it with values directly. Instead, an empty map is created and then filled with values.
Next chapter: Methods