Use the built-in delete() function with the map and the key you want to remove. This operation is safe even if the key does not exist; it simply does nothing in that case.
package main
import "fmt"
func main() {
// Initialize a map
scores := map[string]int{
"alice": 90,
"bob": 85,
"charlie": 78,
}
fmt.Println("Before:", scores)
// Delete a specific key
delete(scores, "bob")
// Attempting to delete a non-existent key is safe (no panic)
delete(scores, "dave")
fmt.Println("After:", scores)
}
If you need to verify whether a key existed before deleting it, use the two-value assignment form of map access. This is useful if your logic depends on whether the key was actually present.
package main
import "fmt"
func main() {
users := map[string]string{
"user1": "Alice",
"user2": "Bob",
}
key := "user1"
// Check existence before deletion
if _, exists := users[key]; exists {
delete(users, key)
fmt.Printf("Deleted %s\n", key)
} else {
fmt.Printf("%s not found, nothing to delete\n", key)
}
// Verify it's gone
if _, ok := users[key]; !ok {
fmt.Println("Key confirmed removed")
}
}
The delete() function does not return a value, so you cannot capture the old value directly during deletion. If you need the value associated with the key before removing it, retrieve it first using the standard map lookup syntax, then call delete().
value, ok := myMap[key]
if ok {
// Use value here
delete(myMap, key)
}
Remember that maps in Go are reference types. If you pass a map to a function and delete a key inside that function, the change is reflected in the original map variable in the caller. There is no need to return the map from the function unless you are creating a new map or performing other transformations.