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.
1 2 3 4 5 | petPetOwnerMap := map[string]string{ "Pet1": "Sarah", "Pet2": "Gary", "Pet3": "Steve", } |
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.
1 | var petPetOwnerMap map[string]string |
Then, we can add key-pair values as follows.
1 2 3 4 | petPetOwnerMap["Pet1"] = "Sarah" petPetOwnerMap["Pet2"] = "Gary" petPetOwnerMap["Pet3"] = "Steve" petPetOwnerMap["Pet4"] = "karl" |
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.
1 2 3 4 5 6 | petPetOwnerMap := make(map[string]string) petPetOwnerMap["Pet1"] = "Sarah" petPetOwnerMap["Pet2"] = "Gary" petPetOwnerMap["Pet3"] = "Steve" petPetOwnerMap["Pet4"] = "karl" |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var petPetOwnerMap map[string]string // Add new map item if key does not exist yet petPetOwnerMap["Pet5"] = "Keane" // Update an item's value if key already exists petPetOwnerMap["Pet5"] = "Luke" // Loop through the map items for key, value := range petPetOwnerMap { fmt.Println(key, value) } // To display the whole map fmt.Println(petPetOwnerMap) |
Working with Golang maps is easy.