Go Reference ยท Built-in Functions
Go delete() function
Reference for Go delete(): remove a key from a map, what happens when the key is missing or the map is nil, and how to delete while ranging safely.
delete() removes one key and its value from a map. If the key is not in the map, nothing happens: there is no error and no return value to check. The same is true for a nil map.
Deleting is the only way to shrink a map by a single entry. To remove all entries at once, use clear() or assign a new map.
ages := map[string]int{"ann": 31, "bob": 25} delete(ages, "bob") // ages is now map[ann:31]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func delete(m map[Key]Value, key Key)
| Name | Description |
|---|---|
m |
The map to change. May be nil. |
key |
The key to remove, assignable to the map's key type. |
Returns: nothing.
Edge cases: a missing key or a nil map is a no-op. A key containing a NaN (for example a float64 key) can never be matched, so delete(m, math.NaN()) does nothing; use clear(m) to remove those entries.
Usage notes
- Deleting during
rangeis safe. An entry removed before the loop reaches it will not be produced. Entries added during the loop may or may not appear. - Check first only if you need to. Since deleting a missing key is harmless, you do not need
if _, ok := m[k]; okbefore it. - Deleting does not shrink memory. The map keeps its buckets, so a map that once held millions of entries still uses a lot of memory after you delete them. Assign a fresh map to let the garbage collector reclaim it.
- Concurrency: a delete counts as a write. Mixing it with other goroutines reading or writing the same map without a lock is a data race and can crash the program (see Maps and concurrency).
- Not for slices. To remove an element from a slice use
slices.Delete()orappend(s[:i], s[i+1:]...). - Sets built as
map[T]struct{}usedeleteto remove members. - Go 1.21 added
clear()for emptying a map in one call.