Delete keys from a map in Go with delete()

Remove entries from a map in Go with the built-in delete(map, key); deleting a missing key is safe; use the comma-ok form first when you want to log or branch on absent keys.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

Delete keys from a map in Go with delete()

The built-in delete(m, k) removes the entry for key k from map m. If k is absent, the call is a no-op—no panic. Other languages call similar structures dictionaries or hash maps; in Python the ideas overlap with a Python dictionary. For Go basics, read maps in Go.

Tested with Go 1.24 on Linux.


Delete without checking

go
package main

import "fmt"

func main() {
	studentsScore := map[string]int{
		"Anna": 5, "Bob": 9, "Clair": 8, "Daniel": 10,
	}
	fmt.Println(studentsScore)
	fmt.Println("Deleting Bob")
	delete(studentsScore, "Bob")
	fmt.Println("Deleting Eve (missing key)")
	delete(studentsScore, "Eve")
	fmt.Println(studentsScore)
}
Output

You should see Bob removed and the map unchanged by the Eve delete beyond losing nothing.


Delete when the key exists

go
package main

import "fmt"

func deleteKey(m map[string]int, key string) {
	if _, ok := m[key]; ok {
		delete(m, key)
	} else {
		fmt.Println(key, "is not in the map")
	}
}

func main() {
	studentsScore := map[string]int{
		"Anna": 5, "Bob": 9, "Clair": 8, "Daniel": 10,
	}
	fmt.Println(studentsScore)
	deleteKey(studentsScore, "Bob")
	deleteKey(studentsScore, "Eve")
	fmt.Println(studentsScore)
}
Output

You should see a line reporting Eve is not in the map, then the map without Bob.


Summary

To golang delete from map data, call delete(m, k); it is safe on missing keys. When you need explicit handling, gate the delete with the comma-ok read. Pair deletes with clear map semantics from your functions or methods so callers know whether absence is normal.


References


Frequently Asked Questions

1. What happens if I delete a key that is not in the map?

Nothing harmful; delete is a no-op for missing keys and does not panic.

2. How do I delete only when the key exists?

Use if _, ok := m[k]; ok { delete(m, k) } or a small helper function.

3. How do I clear an entire map?

Loop keys and delete, or assign a new map from make, or for large maps consider replacing the variable with a fresh map so the old one can be collected.

4. Can I delete while ranging a map?

You may delete keys you have not started iterating yet; deleting keys you are about to visit is not defined—usually copy keys first or collect removals then apply them.

5. Where is map usage covered in depth?

See maps in Go for creation, iteration, and the zero value.
Tuan Nguyen

Data Scientist

Proficient in Golang, Python, Java, MongoDB, Selenium, Spring Boot, Kubernetes, Scrapy, API development, Docker, Data Scraping, PrimeFaces, Linux, Data Structures, and Data Mining. With expertise …