How to delete or remove a key from a map in Golang?

After adding some key-value pairs, we may want to delete or remove a key from the map. Go language provides us with the built-in delete function which helps us to delete or remove a key from the map.

Syntax for the delete function

delete function accepts two parameters – one will be the map itself and the second will be the key that we want to delete from that map.

delete(mapName,keyName)
Code example
package main

import (
	"fmt"
)

func main() {

	theMap := make(map[string]int)

	theMap["first"] = 10
	theMap["second"] = 20
	theMap["third"] = 30
	theMap["fourth"] = 40

	fmt.Println("Map contents before:", theMap)

	// deleting key "third" from the map
	delete(theMap, "third")

	fmt.Println("Map contents after:", theMap)

}

Output –

Map contents before: map[first:10 fourth:40 second:20 third:30]
Map contents after: map[first:10 fourth:40 second:20]

We have successfully deleted the “third” key from the map.

But what if we try to delete a key that does not exist on the map?

In this scenario, the delete() function won’t cause any panic without any changes to the map.

package main

import (
	"fmt"
)

func main() {

	theMap := make(map[string]int)

	theMap["first"] = 10
	theMap["second"] = 20
	theMap["third"] = 30
	theMap["fourth"] = 40

	fmt.Println("Map contents before:", theMap)

	// deleting key "codekru" from the map,
	// that do not exist in the map
	delete(theMap, "codekru")

	fmt.Println("Map contents after:", theMap)

}

Output –

Map contents before: map[first:10 fourth:40 second:20 third:30]
Map contents after: map[first:10 fourth:40 second:20 third:30]

Related Articles –

Hope you have liked our article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.