How to Delete a Key from a Map in Golang

To delete a key from a Map in Golang, you can use the “delete()” function. When you delete a key from a map, the deleted value is the key-value pair like a single entity.

Syntax

delete(map, key)

Parameters

It accepts map and key as arguments.

  1. map: The map from which you want to delete a key-value pair.
  2. key: The key you want to remove and its associated value from the map.

Return value

It returns nothing, as this operation affects the original map.

Example

package main

import (
  "fmt"
)

func main() {
  mainMap := map[string]int{
    "first": 1,
    "second": 2,
    "third": 3,
 }

 fmt.Println("Before deletion:", mainMap)

 // Delete the key "third" from the map
 delete(mainMap, "third")
   fmt.Println("After deletion:", mainMap)
}

Output

Before deletion: map[first:1 second:2 third:3]
After deletion: map[first:1 second:2]

In this example, we created a map called mainMap with three string keys (“first”, “second”, and “third”) and their corresponding integer values (1, 2, 3).

We then printed the map before deletion, deleted the key “third” using the delete() function, and finally printed the map again after deletion.

The output will show that the key “third” and its associated value have been removed.

If you try to delete a key that does not exist in the map, the delete() function will do nothing, and the program will not raise any errors.

Leave a Comment