Golang map guide: check if map has key, delete a key, iterate over a map and more.

4 min read

Initalizing, iterating, deleting and check if map has key in Golang

Go is a powerful programming language that offers a rich set of data structures. A common one you'll be using is the map data structure. In this blog post, we will explore Go maps, understand their characteristics, and demonstrate their practical usage through code examples such as populating, iterating over and how to check if map has key.

Understanding Go Maps

Go maps are unordered collections of key-value pairs that provide efficient data organization and retrieval. They are analogous to dictionaries or hash tables in other programming languages. Maps in Go are implemented as hash tables, which offer fast lookup and insertion times, even with large amounts of data.

Declaring and Initializing Maps:

To declare a map variable in Go, you use the map keyword followed by the key and value types enclosed in square brackets. Here's an example:

var newMap map[string]string

In the above example, newMap is declared as a map with keys of type string and values of type string. However, this declaration alone doesn't create an initialized map. To declare and initialize the map, you can use the make function, or you can also create an empty map using curley brackets {}:

newMap := make(map[string]string) newMap := map[string]string{}

Adding and Retrieving Elements

Once a map is initialized, you can add key-value pairs to it using the syntax newMap[key] = value. Here's an example:

newMap["title"] = "hello world!" newMap["article"] = "this is a test"

To retrieve the value associated with a particular key, you can use the syntax value := newMap[key]. For instance:

fmt.Println(newMap["title"]) // Output: hello world!

If the key is not present in the map, Go returns the zero value for the value type. In the case of int, the zero value is 0, and for a string that would be an empty string. In the case of a pointer, you would expect to see a nil.

Check if map has key

To check if a map if a key exists, you can use the following syntax:

value, ok := newMap[key]

The value variable will hold the value associated with the key, and the ok variable will be true if the key exists, or false otherwise. Here's an example:

title, exists := newMap["title"] if exists { fmt.Println("the title is:", title) } else { fmt.Println("Could not find title") }

Because in Golang we like to return early on failures, it's quite common to see this specific golang map check if key exist if statement to validate if a value exists or not:

newMap := map[string]string{"title": "hello world!"} if _, ok := newMap["title"]; !ok { return errors.New("title not found") } fmt.Println(newMap["title"])

Deleting Key-Value Pairs

To remove a key-value pair from a map, you can use the delete function with the map and the key as arguments:

delete(newMap, "title")

After executing this code, the key-value pair with the key "apple" will be removed from the map.

Iterating Over a Map

Go provides a range keyword to iterate over maps. When used with a map, it returns the key and value for each key-value pair in the map. Here's an example:

for key, value := range newMap { fmt.Println(key, value) }

The above code will print all the key-value pairs in the newMap map, not necessarily in order, which is by design. We've previously discussed this in the For Loops in For Loops Golang: A Comprehensive Guide, and explained the reasoning behind this design consideration.

In summary

Go maps are a powerful data structure for organizing and retrieving data efficiently. They offer fast lookup and insertion times, making them ideal for various applications. In this blog post, we explored the basics of Go maps, including declaration, initialization, adding and retrieving elements, check if map has key, deleting key-value pairs, and iterating over maps.

Regardless of whether you're building web applications, data processing systems, or any other Go project, maps will undoubtedly prove to be highly valuable.