Maps are a fundamental data structure in most programming languages. Maps refer to a collection of key-value pairs used to store unordered data. In other programming languages, maps are referred to as dictionaries, hash, associative array, hash map, or unordered maps.

No matter the name, maps provide versatility, fast and efficient data looks, updates, and deletes using the set of unique keys.

The primary focus of this tutorial is to guide you through creating and using maps in the go programming language.

Go create map

There are two ways to create a map in the go programming language.

Map Literal

The first method is to use a keyword map followed by the data type of the key (enclosed in square brackets) and the data type of the values.

Once you have the map defined, you can insert the set of key-value pairs inside a pair of curly braces.

The syntax is as shown:

map[key]value {


   key: value

}

Maps are very useful when storing related data, such as user information. For example, the following code creates a map storing user information.

    user_info := map[string]string{


        “id”:         “1”,


        “name”:       “Jonh Doe”,


        “department”: “Game Developer”,


        “salary”:     “$140,000”,


        “country”:    “Bulgaria”,


    }

Note that the key-value pairs of the map are enclosed inside the curly braces. The value on the left of the colon represents the key, while the value on the right represents the associated value.

In the above example, we format the key-value pairs as JSON for easier readability; however, you can have a one-liner as:

user_info := map[string]string{


        “id”: “1”, “name”: “Jonh Doe”, “department”: “Game Developer”, “salary”: “$140,000”, “country”: “Bulgaria”,


    }

Ensure to separate each key-value pair with a comma.

Functional Approach

The second method you can use to create a map in go is the make function. This is a built-in function that allows you to pass the type of the map to create. It returns an initialized map. The syntax is as shown below:

make(map[key_type]value_type)

The function will return an empty map.

You can assign a map to a variable like other programming languages, as shown in the examples above.

To view the key-values in the array, you can use the fmt.println method as shown in the example below:

package main

import “fmt”

func main() {


    user_info := map[string]string{


        “id”: “1”, “name”: “Jonh Doe”, “department”: “Game Developer”, “salary”: “$140,000”, “country”: “Bulgaria”,


    }


    fmt.Println(“maps:”, user_info)

}

The code above should return the output as shown:

::output


maps: map[country:Bulgaria department:Game Developer id:1 name:Jonh Doe salary:$140,000]

Accessing Map Items

To get the value stored in a map, you can use its unique key. Golang should return the value associated with the specified key.

For example:

fmt.Println(user_info[“name”])

The above snippet should return the value associated with the key “name” from the user_info map.

The output is as shown”

Since each key in a map is unique, the code above should always return a single value associated with a key if exists.

Hence, making use of maps is efficient for related information.

Map Iteration

The next question comes, how do you iterate over the items in a map? Unlike other programming languages, which provide built-in functions to fetch keys and values, go does not.

However, it allows you to iterate over a map using the range operator.

Let’s take the example user_info map we created earlier. We can use the range operator to iterate over the keys and values of the map, as shown in the example code below:

    for k, v := range user_info {


        fmt.Printf(“%q -> %qn, k, v)


    }

In the above code, go will iterate over the items and return each key and its associated value. Note that go will create the variables with the set type. For example, both the key and value are strings; hence, we can use the %q formatter to print its value using the printf function.

The resulting output is as shown:

“id”> “1”

“name”> “Jonh Doe”

“department”> “Game Developer”

“salary”> “$140,000”

“country”> “Bulgaria”

What happens when you need to access the keys only? You can declare a variable to store the keys and then use the range operator in such a scenario.

Consider the example shown below:

    keys := []string{}


    for k := range user_info {


        keys = append(keys, k)


    }


    fmt.Printf(“%q”, keys)

In the example above, we start by defining a slice to store the keys from the map. We then use the range operator to iterate over the keys and append each key to the slice.

Finally, we print the keys using the printf method. The resulting output is as shown:

[“id” “name” “department” “salary” “country”]

You apply the same technique above to get the values of a map.

Map Length

In golang, you can get the length of a map using the len method. This returns the number of items on the map.

For example:

fmt.Println(len(user_info))

Number of items on the map is:

Add, Update, Delete Keys and Values

In Go, maps are mutable. This means that you can add, delete, or update existing items in the map.

Let us look at a few examples of how to perform such operations.

Add new Item

To add a new item to a map, reference the name of the map followed by the key in square brackets and a single sing (=) to assign a new value.

The syntax is as shown:

Let us add a new key to the user_info map as shown in the example below:

user_info[“dob”] = “06/06/1995”

In the example above, we add a new item called “dob” to the user_info map. Keep in mind that items on the map are unordered. Hence, adding a new item does not mean it will appear as the last or first item on the map.

Update an Item

Suppose we need to change a piece of information about the user. For example, say the user got a raise (yay!), and we need to update the info.

We can use a similar syntax as adding a new key. However, we reference an existing key in the map in this case.

An example is as shown:

user_info[“salary”] = “$160,000”

The above code should change the value of the “salary” key to the new specified value.

The resulting output is as shown:

The output is as shown:

[country:Bulgaria department:Game Developer dob:06/06/1995 id:1 name:Jonh Doe salary:$160,000]

Note the new value of the salary key is updated to reflect the new data.

HINT: A better way to think of it is, if the item exists, update the value; otherwise, create a new item.

Delete an item

Go also allows you to delete an item from the map. We use the delete() method, which takes two arguments.

The first argument is the name of the map variable under which to delete an item, and the second is the key to delete.

Look at the example shown below:

delete(user_info, “department”)


fmt.Println(user_info)

The function will delete the “department” from the user_info map. The resulting map is as shown:

map[country:Bulgaria id:1 name:Jonh Doe salary:$140,000]

Clear a Map

Suppose you want to clear a map of all the existing items? To do this, you can set the values to an empty map with the same key and value type.

For example:

user_info = map[string]string{}

The above example should re-initialize the user_info map to an empty map.

HINT: Maps are unordered collection, and operations such as iterations will not always result in the same order of items. If the order is a necessity, consider another data type.

Conclusion

In this guide, we explored maps in the go programming language. Using maps, you can create a set of unordered items and use each unique key to access the items. This removes the need for indexes to access items.

Thank you for reading, and come back for more Go tutorials.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2022/02/echo/john-150×150.png621352ab9128d.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list