Maps

A map in GO is a key-value structure that allows you to store values tagged with key names, and then look the value up by the key. Creating maps in GO is a two step process. First, you have to declare the map, then you use the make function we used when we created slices.

Declaring and Using Maps



var myMap map[string] int
myMap = make(map[string] int)


The first line declares a map of string keys with int values. The second line actually creates the map. This is verbose and cumbersome. There is a simpler way:

myMap := make(map[string] int)

This is like a quick assignment in GO. It's still verbose, but better.

Once you've set up your map, using it is similar to other languages.


myMap["New York"] = 1
myMap["London"] = 2


is how values are assigned to keys in the map. As in other languages, you can declare, make, and assign at the same time.

myMap := map[string] int {"New York" : 1, "London" : 2}

Two things I need to remember are first, the parentheses are missing in this form. Also, there is no "=" sign between the data type and initializers which most other languages use.

You can also create an empty map by using an empty set of braces.

Accessing Values and Zero Values




Once you have a map you can access values by referencing the key.

fmt.Println(myMap["New York"])

will print 1 in my example. Unlike other languages, if you access a non-existent key, you don't get an error, or a nil value in GO. Instead you get a zero value, or an empty string.

fmt.Println(myMap["Chicago"])

will return "" (the zero value for strings).

However, you will get nil if you try to access a map you've declared but not created.

fmt.Println(yourMap["apple"])

will return nil.

An interesting feature of GO is that each item in the map actually returns two values, the assigned value and a boolean that indicates if the zero value returned is actually a nil. Ugh!

value, ok = myMap["New York"]

returns 1,true while

value, ok = myMap["Chicago"]

returns 0,false. The reason for this is to allow you to differentiate a 0 that has been assigned from a 0 that actually means nil. There is a reason why GO chose this, but for me, this is old-school binary thinking. Most languages just return a nil.

Deleting Map Items



To remove an item from a map you use the following syntax:

delete(myMap, "London")

you pass in the name of the map and the key-value to be removed.


That's enough for now. More on maps next time.






This site does not track your information.