Go, Software Development

Three Ways To Create Maps In Golang

A map is a ubiquitous data structure that allows us to store key-value pairs, and there are three ways to create maps in Golang. Also, it is one of the reference types in Golang that allows us to change its content without using pointers. Sometimes, we refer to it as a dictionary in some programming languages, but the concept is similar.

Option 1: Declare And Initialize Map At The Same Time

The first option to create maps in Golang is similar to creating a struct instance with values. For example, consider the following codes with a map that stores the pet’s name and its owner.

The codes use the map keyword and two data types for the keys and values. For instance, the string type within the square braces represents the data type for the keys, while the string type before the curly braces is the data type for the values. Then, within the curly braces, we specify the key-pair values using semi-colons and commas between the pairs. The last key-pair value must still use a comma, even if it is the only pair in the map declaration.

Option 2: Create An Empty Golang Maps

Sometimes, we want to start with an empty Golang map and fill it with values later. For instance, consider the following codes.

Then, we can add key-pair values as follows.

Option 3: Another Way to Create An Empty Map

The third option to create a map in Golang includes using a built-in function make. For example, we have the following codes.

We pass the map construct map[string]string to the make function in the codes. Then, it returns a blank Golang map that we can fill in with data later.

Operations on a Golang Map

We have seen how we can add (or update) map items. In addition to that, we can also loop through the map or delete its items. For example, we have the following codes that perform all three operations after creating an empty Golang map.

Working with Golang maps is easy.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like