golang

Map Removal in Go (Remove from Map)

In Go, maps refer to a data structure that allows us to store the key-value pairs. Maps are extremely versatile and play an important role when building complex and real-world applications. You will often hear maps referred to dictionaries, associative arrays, or hash maps in other programming languages.In this tutorial, we will delve into the world of maps in Go and learn about the map deleting elements from a map.

Golang Maps

Before we dive into map copying, let us start with the fundamentals of maps in Go.

Declaration

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

The syntax is as follows:

var m map[KeyType]ValueType

An example is as follows:

var m map[string]int

Initialization

Before we can use a map, we need to initialize a map. In Go, we can do this using the “make” function as follows:

m := make(map[string]int)

Adding and Accessing the Elements

Once we initialize a map, we can add the elements to a map by assigning a value to a specific key.

An example is as follows:

m["MySQL"] = 3306
m["PostgreSQL"] = 5094

To access the value that is associated with a key, use the key within the square brackets as shown in the following example:

fmt.Println(m["PostgreSQL"])

This should return the value that is associated with the specified key.

Remove the Elements from a Map

Let us now proceed and discuss the various methods that we can use to remove the elements from a map.

Method 1: Using the Delete Function

The most common method of removing a key-value pair from a map in Go is using the delete() function.

The “delete” function is a built-in function from the Go standard library that allows us to remove a given pair from a map.

The function accepts the map and the key that we wish to remove as arguments as demonstrated in the following example:

package main
import (
    "fmt"
)
func main() {
    m := make(map[string]int)
    m["MySQL"] = 3306
    m["PostgreSQL"] = 5049
    m["MongoDB"] = 27071
    m["Redis"] = 6359
    fmt.Println("Initial Map:", m)
    // Method 1: Using the delete() function
    delete(m, "Redis")
    fmt.Println("After:", m)
}

In the given example, we use the “delete” function and pass the map and the key of “Redis” from the dictionary.

The resulting output is as follows:

Initial Map: map[MongoDB:27071 MySQL:3306 PostgreSQL:5049 Redis:6359]
After: map[MongoDB:27071 MySQL:3306 PostgreSQL:5049]

Method 2: Check Before Deleting

It is a good technique to check that the key exists in the map before deleting it. This is incredibly useful when you need to prevent the runtime panics when attempting to delete a non-existing key.

In Go, we can check if a key exists using the comma-ok idiom which is expressed as follows:

(_, exists := map [key]).

If the key exists, we can safely delete it using delete().

package main
import (
    "fmt"
)
func main() {
    m := make(map[string]int)
    m["MySQL"] = 3306
    m["PostgreSQL"] = 5049
    m["MongoDB"] = 27071
    m["Redis"] = 6359
    fmt.Println("Initial Map:", m)
    key := "Redis"
    if _, exists := m[key]; exists {
        delete(m, key)
    } else {
        fmt.Printf("Key '%s' not found in the map.\n", key)
    }
}

This allows us to check the existence of the key before deleting.

Method 3: Deleting Multiple Keys

We can also take advantage of basic loops in Go to remove multiple keys from an existing map. This makes it useful when you need to perform a batch delete without copying and pasting the same “delete” function.

We can start by creating a slice of the keys that we wish to delete and iterate through them. We can then apply the delete() function for each key.

package main
import (
    "fmt"
)
func main() {
    m := make(map[string]int)
    m["MySQL"] = 3306
    m["PostgreSQL"] = 5049
    m["MongoDB"] = 27071
    m["Redis"] = 6359
    fmt.Println("Initial Map:", m)
    delete_me := []string{"PostgreSQL", "Redis"}
    for _, key := range delete_me {
        delete(m, key)
    }
    fmt.Println("After:", m)
}

Output:

Initial Map: map[MongoDB:27071 MySQL:3306 PostgreSQL:5049 Redis:6359]
After: map[MongoDB:27071 MySQL:3306]

Method 4: Delete the Entire Map

In other cases, we might need to remove all the key-value pairs from the map and start with an empty map.

This basically involves creating a new map using the “make” function as follows:

m = make(map[string]int)

fmt.Println("After:", m)

That should clear the map.

Conclusion

In this tutorial, we learned all about map removal in Go. We learned how to add the elements in a map, access the elements in the map, and remove the elements from it.

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