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 ...