golang

Map Printing in Golang (Print Map)

One of the most fundamental and crucial data structures in the Go ecosystem is the map. Maps allow us to store the key-value paired collections. This makes it very useful when we need to store the associative values with unique keys.

In this tutorial, we will learn the basics of working with maps in Go and explore the various methods and techniques that we can use to print the maps.

Golang Maps

In Go, a map refers to an unordered collection of key-value pairs where each key is unique. You can think of a map like a dictionary in languages such as Python or associative array in PHP.

In Go, we declare a map using the “map” keyword followed by the key and value types enclosed in square brackets.

An example syntax is as follows:

var mapName map[KeyType]ValueType

Here, the KeyType refers to the type of keys in the map and the ValueType refers to the type of values associated with each key.

We can also create and initialize a map using the “make” function as shown in the following example:

mapName := make(map[KeyType]ValueType)

Working with Maps in Go

To add a key-value pair to a map, we can simply use the assignment operator (=) as shown in the following example:

mapName[key] = value

To retrieve a value from a map based on a key, use the key within the square brackets.

result := mapName[key]

To check if a key exists in a map, we can use a two-value assignment where the second value represents a Boolean which indicates whether the key exists:

value, exists := mapName[key]
if exists {
    // Key exists, use the 'value'
} else {
    // Key does not exist
}

To remove a key-value pair from a map, we can use the “delete” function.

delete(mapName, key)

We can iterate over the keys and values of a map using a “for” loop with a range clause as follows:

for key, value := range myMap {

  // code

}

Once we covered the basics of working with maps in Go, let us explore the various methods and techniques for printing the maps.

Print a Map in Go

There are various methods that we can employ to print the contents of a Go map. Each method depends on what data you are interested in and how you want to display it.

The following are some of the most common techniques that you can use.

Print the Key-Value Pairs

If you are interested in printing out both the key and associated value, you can use a basic “for” loop as shown in the following example:

vars := map[string]int{"one": 1, "two": 2, "three": 3}
for key, value := range vars {
    fmt.Printf("Key: %s, Value: %d\n", key, value)
}

This should iterate over the map and return the resulting key and value from the map.

Print the Keys Only

In some cases, you may only be interested in the keys of the dictionary and not the associated value. For that, you can also use a “for” loop but extract the specific component from the map as follows:

for key := range vars {
    fmt.Printf("Key: %s\n", key)
}

This should return the keys of the map.

Print the Values Only

The same case applies when you are only interested in the values of the dictionary and not the keys.

for _, value := range vars {
    fmt.Printf("Value: %d\n", value)
}

Custom Formatting

We can also customize the format in which we print the map using the formatting specifiers of the “fmt” package.

For example, we can use Printf with a custom format specifier to control the output format as shown in the following example:

for key, value := range vars {

   fmt.Printf("%s: %d, ", key, value)

}

In this case, the previous code should print the key and value pairs, separated by commas.

JSON Serialization

Another technique of printing the map values is basically serializing the map object into a JSON string using the encoding/JSON package.

An example is as follows:

import (
    "encoding/json"
    "fmt"
)

vars := map[string]int{"one": 1, "two": 2, "three": 3}
jsonData, err := json.Marshal(vars)
if err != nil {
    fmt.Println(err)
} else {
    fmt.Println(string(jsonData))
}

This should convert the map into a JSON string and print it out.

Conclusion

In this post, we explored the various methods and techniques that we can use to print the map contents in Go.

About the author

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