Go Map Project

Go Map, The Key/Value Type

 

In programming, the map, sometimes called a hash, a hash table, a dictionary, or an associative array is a data type that maps keys to associated values. You could think of a Go Map as a Rolodex or phone book. To find someone’s contact information you quickly look them up by name (the key) to get their phone number (the value) that you saved for them.

Unlike the other variables we’ve talked about including arrays, the Go Map has two values. Both the key and the value have a type associated to them. Map keys must be a type that is comparable, for now, take this to mean types besides arrays, slices, functions (which we haven’t talked about yet), and Maps. Map values, however, can be any type, including other Maps!

Go Map diagram

Go Map Literals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package main

import (
    "fmt"
)

func main () {
    myMap := map[string]string{
        "Lisa Smith": "521-8976",
        "John Smith": "521-1234",
        "Sandra Dee": "521-9655",
    }

    fmt.Println(myMap)
}

Most of this should start to feel very familiar to you. What’s new that we’ve introduced is the actual Go Map declaration format. You declare a Map with the map keyword followed by the key type in brackets, with the value type following immediately after the brackets.

Go Map Initialization

In Go when you declare a variable without setting its value it’s value is set to the “zero value” for its type. The zero value for number types is, well, 0. The zero value for strings is an empty string, and the zero value for arrays is an empty array. The zero value of a Go Map is nil.

An essential difference between the Go Map and other types that we’ve learned so far is that you cannot assign values to a nil Map. To assign values to a Map, you must initialize it. Attempting to assign values to a nil Map will cause your program to crash! That’s is why we started with a Map literal since we’re declaring and initializing a literal at the same time.

To initialize a Go Map that we’ve declared so that it no longer has a nil value we use the make() function. The make function creates an empty map with our key and value types and assigns it the variable that holds our Go Map.

1
2
var myMap map[string]string
myMap = make(map[string]string)

The make function expects the same format that we use to declare a Map. Declaring and then initializing a Go Map is functionally equivalent to creating an empty Map literal.

1
var myMap = map[string]string{}

Setting Go Map Keys

Once we have a Go Map declared and initialized setting keys is easy. The syntax for setting a Map key is the same as setting the value of an array or slice index.

1
2
3
4
5
6
7
8
var myMap map[string]string
myMap = make(map[string]string)

myMap["Lisa Smith"] = "521-8976"
myMap["John Smith"] = "521-1234"
myMap["Sandra Dee"] = "521-9655"

fmt.Println(myMap)

Reading Go Map Keys

Just like with setting the value of a Go Map key, reading the value of a key uses the same syntax as reading the value of an array index.

1
2
3
4
5
6
7
8
var myMap map[string]string
myMap = make(map[string]string)

myMap["Lisa Smith"] = "521-8976"
myMap["John Smith"] = "521-1234"
myMap["Sandra Dee"] = "521-9655"

fmt.Println(myMap["Lisa Smith"])

Checking if a Go Map Key Exists

There is a gotcha with reading Go Map keys, however. When you read a Map key that doesn’t exist it returns the zero value for the value type. If we try to read the key “Jane Doe” from our Go Map, it will return an empty string. Is this because Jane Doe does not exist in our Map or because Jane Doe is in the Map but we didn’t know her phone number and left it blank?

Fortunately, Go offers us a trick that tells us whether the value we read from the Map exists. In our previous examples of reading a Map key, we assigned the value of the Map key to a variable. However reading a Map key can return two values, not just the value of the key. The second value reading a key returns is a boolean value that will be true if the Go Map key exists and false if it’s not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
    "fmt"
)

func main () {
    var myMap map[string]string
    myMap = make(map[string]string)

    myMap["Lisa Smith"] = "521-8976"
    myMap["John Smith"] = "521-1234"
    myMap["Sandra Dee"] = "521-9655"

    phoneNumber, ok := myMap["Jane Doe"]
    if ok {
        fmt.Println("Jane's number is", phoneNumber)
    } else {
        fmt.Println("Jane isn't in our map!")
    }
}

Deleting From a Go Map

So, now we know how to create a Map, how to write to a Map, and how to read from a Map. The last thing to make Maps truly useful is to be able to delete from a Map. To remove a key from a Go Map, we use the built-in delete() function. The delete function takes two arguments. The first argument is the Map that we want to delete from, and the second argument is the key that we want to remove. Unlike the append() function with slices, delete directly modifies the Map that we’re deleting from instead of returning a new Map with the key deleted.

1
delete(myMap, "John Smith")
Chris Sotherden

Originally a native of upstate NY, I relocated to North Carolina in 2013 where I've since helped open the new R&D headquarters for Optanix. I've been with Optanix (formerly ShoreGroup) for over ten years, where I've worked my way up from entry-level to Lead Architect. I taught myself programming in high school and am an all around technology nerd from the design of programming languages and compilers, to quantum computing, and rockets. Outside of technology I've competed in powerlifting and medium distance running, as well as smoking some mean BBQ. Oh, my partner and I also breed, show, and sell fancy goldfish!

>