How to delete a key from a map in Golang?


To delete a key from a map, we can use Go's built-in delete() function. It should be noted that when we delete a key from a map, its value will also be deleted as the key-value pair is like a single entity when it comes to maps in Go.

Syntax

The syntax of the delete function is shown below.

delete(map,key)

Once we call the function in the above format, then the key from the map will be deleted.

Now, let's use the above function in Go code and understand how it works.

Example 1

Consider the code shown below

package main

import (
   "fmt"
)

func main() {
   m := make(map[string]int)
   m["mukul"] = 10
   m["mayank"] = 9
   m["deepak"] = 8

   fmt.Println(m)

   fmt.Println("Deleting the key named deepak from the map")

   delete(m, "deepak")

   fmt.Println(m)
}

In the above code, we have a map with the name m which contains some strings as keys and some integer values are the value of those keys. Later, we make use of the delete() function to get rid of the key named "deepak" from the map and then we again print the contents of the map.

If we run the above code with the command go run main.go then we will get the following output in the terminal.

Output

map[mukul:10 mayank:9 deepak:8]
Deleting the key named deepak from the map
map[mukul:10 mayank:9]

The above code will work fine in most of the examples, but in one case it will cause a panic. The case that it will cause a panic is the one in which we aren't sure if a particular key even exists in the map or not.

Example 2

To make sure we don't write a code that creates panic, we can make use of the code shown below.

package main

import (
   "fmt"
)

func main() {
   m := make(map[string]int)
   m["mukul"] = 10
   m["mayank"] = 9
   m["deepak"] = 8

   fmt.Println(m)

   fmt.Println("Deleting the key named deepak from the map")

   if _, ok := m["deepak"]; ok {
      delete(m, "deepak")
   }

   fmt.Println(m)
}

The above approach is more fail-safe and is recommended over the first one.

Output

If we run the above code with the command go run main.go then we will get the following output in the terminal.

map[mukul:10 mayank:9 deepak:8]
Deleting the key named deepak from the map
map[mukul:10 mayank:9]

Updated on: 02-Sep-2023

54K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements