Go Map Basics

Glitch
2 min readMar 14, 2023

--

Go is a powerful and efficient programming language that is widely used in the development of modern software applications. One of the core data structures in Go is a map, which provides a powerful and flexible way to store and retrieve data.

In this blog post, we will take a closer look at maps in Go and explore some of the key features and capabilities of this data structure.

What is a Map in Go?

A map is a built-in data structure in Go that allows you to store key/value pairs. It is similar to a dictionary or hash table in other programming languages. A map is created using the make() function and can be initialized with a set of key/value pairs.

Here is an example of how to create a map in Go:
m := make(map[string]int)
In this example, we create a map with string keys and integer values. The make() function is used to create a new empty map.

Inserting Data into a Map

To insert data into a map, you can simply assign a value to a key. For example:
m["one"] = 1
m["two"] = 2
m["three"] = 3
In this example, we assign integer values to the string keys "one", "two", and "three".

Retrieving Data from a Map

To retrieve data from a map, you can use the key as an index. For example:
fmt.Println(m["one"])
This will print the value associated with the key "one", which is 1.

If the key does not exist in the map, Go will return the zero value for the value type. For example:
fmt.Println(m["four"])
This will print 0, because "four" is not a key in the map.

Iterating Over a Map

You can iterate over the keys and values in a map using the range keyword. For example:
for key, value := range m {
fmt.Println(key, value)
}
This will print out all of the key/value pairs in the map.

Deleting Data from a Map

To delete a key/value pair from a map, you can use the delete() function. For example:
delete(m, "one")
This will delete the key "one" and its associated value from the map.

Conclusion

Maps are a powerful and flexible data structure in Go that allow you to store and retrieve key/value pairs. They are easy to use and provide a simple interface for working with data. By understanding how maps work and how to use them effectively, you can take your Go programming skills to the next level.

--

--