Declaration and Initialization
This lesson describes the important concepts regarding maps, i.e., how to use, declare and initialize them.
We'll cover the following
Introduction
Maps are a special kind of data structure: an unordered collection of pairs of items, where one element of the pair is the key, and the other element, associated with the key, is the data or the value. Hence they are also called associative arrays or dictionaries. They are ideal for looking up values, and given the key, the corresponding value can be retrieved very quickly.
This structure exists in many other programming languages under other names such as Dictionary (dict
in Python), hash
, HashTable
and so on.
Concept
A map is a reference type and declared in general as:
var map1 map[keytype]valuetype
For example:
var map1 map[string]int
(A space is allowed between [keytype]
and valuetype
, but gofmt
removes it.)
The length of the map doesn’t have to be known at the declaration, which means a map can grow dynamically. The value of an uninitialized map is nil. The key type can be any type for which the operations == and != are defined, like string, int, and float. For arrays and structs, Go defines the equality operations, provided that they are composed of elements for which these operations are defined using element-by-element comparison. So arrays, structs, pointers, and interface types can be used as key type, but slices cannot because equality is not defined for them. The value type can be any type.
Maps are cheap to pass to a function because only a reference is passed (so 4 bytes on a 32-bit machine, 8 bytes on a 64-bit machine, no matter how much data they hold). Looking up a value in a map by key is fast, much faster than a linear search, but still around 100x slower than direct indexing in an array or slice. So, if performance is very important try to solve the problem with slices.
If key1
is a key value of map map1
, then map1[key1]
is the value associated with key1
, just like the array-index notation (an array could be considered as a simple form of a map, where the keys are integers starting from 0). The value associated with key1
can be set to (or if already present changed to) val1
through the assignment:
map1[key1] = val1
The assignment:
v:= map1[key1]
stores the value in v
corresponding to key1
. If key1
is not present in the map,
then v
becomes the zero-value for the value type of map1
.
As usual len(map1)
gives the number of pairs in the map, which can grow or diminish because pairs may be added or removed during runtime.
Maps are reference types, as memory is allocated with the make
function. Initialization of a map is done like:
var map1 map[keytype]valuetype = make(map[keytype]valuetype)
or shorter with:
map1 := make(map[keytype]valuetype)
Run the following program to see how maps are made in Go.
Get hands-on with 1400+ tech skills courses.