Delete and clear entries
Delete and clear entries
delete(m, key) removes a key and its associated value. Deleting a missing key does nothing. clear(m) removes all entries and is available from Go 1.21. Neither operation returns a result.
package main
import "fmt"
func main() { m := map[string]int{"tea": 3, "rice": 4} delete(m, "tea") delete(m, "missing") _, ok := m["tea"] fmt.Println(len(m), ok, m["rice"])}After deletion, reading tea produces zero and false with comma-ok. Deleting a key is different from assigning zero: assignment leaves the entry present.
Expected output:
1 false 4Empty a map while keeping it usable
package main
import "fmt"
func main() { m := map[string]int{"a": 1, "b": 2} clear(m) fmt.Println(len(m), m == nil) m["c"] = 3 fmt.Println(m["c"], len(m))}Clearing a non-nil map does not set it to nil. You can insert again without calling make. The language does not promise that deleting entries or clearing releases the allocated storage immediately.
Expected output:
0 false3 1Try it locally
Create two entries, delete one, print its presence and length, clear the map, then print its length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 03: Delete and clear entries
Check the lesson objective before moving on.
What happens if delete targets an absent key?
What is true after clear on a non-nil map?