Deleting Map Elements
Start with Deleting Map Elements
The built-in delete function removes an entry identified by its key. Removing a missing key is safe and has no effect.
What you’ll learn
- Explain the main purpose of deleting map elements.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Call delete(m, key) to remove a matching entry. The function does not return the deleted value or a success boolean. If you need to know whether an item existed, perform a comma-ok lookup first.
Deleting while iterating over a map is allowed, but map traversal order is still unspecified and the details of which not-yet-visited entries appear can depend on mutations. For predictable demonstrations, inspect particular keys or sort a separately collected key list.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
prices := map[string]int{"pen": 10, "book": 50}
before := len(prices)
delete(prices, "pen")
delete(prices, "missing")
_, hasPen := prices["pen"]
fmt.Println("Before:", before)
fmt.Println("After:", len(prices))
fmt.Println("Has pen:", hasPen)
}
Output
Before: 2
After: 1
Has pen: falseTrace what the program does
The map starts with two entries. Deleting pen removes one key; deleting missing does nothing. The final length is one, and the existence lookup for pen reports false.
Avoid common mistakes
deletedoes not return a status result.- Deleting a missing key is not an error, so check existence separately if you need to report it.
Try it yourself
Delete book, then add a new item. Print the map length before and after both changes.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Deleting Map Elements in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.