From charlesreid1

Revision as of 14:53, 13 December 2018 by Admin (talk | contribs) (Created page with "Go maps are data structures that use a hash table under the hood to provide fast, O(1) lookup of key-value pairs. =Basics= ==Initialization== To declare a map type, use the...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Go maps are data structures that use a hash table under the hood to provide fast, O(1) lookup of key-value pairs.

Basics

Initialization

To declare a map type, use the notation:

map[KeyType]ValueType

Example: declare a variable that is a map of string keys to integer values:

var m map[string]int

Like pointers/slices, map types are reference types, so if they are not initialized with a value, they have a nil value. A nil map has not been initialized and so has no underlying space in memory, so you cannot write to a nil map.

To initialize space for a map:

m = make(map[string]int)

The make function allocates space in memory for the hash table. It returns a map value pointing to this location in memory. It is important to note that the actual implementation of a map is not specified by the language, so it depends on the implementation of the Go runtime being used.

Working with maps

To set a key value pair:

m["route"] = 66

To look up a key and assign the value to a variable:

i := m["route"]

Unlike Python, if a key does not exist, Go will return the value type's zero value. For integers, the value is 0; for strings, empty string; for booleans, False; etc.

j := m["root"]
// j == 0

Two useful built-in functions are length (len) and delete (delete):

// number of items in a map
n := len(m)

// remove the specified key from the map
delete(m, "route")