Deletion of map elements
The built-in function
delete
removes the element with keyk
from a mapm
. The valuek
must be assignable to the key type ofm
.delete(m, k) // remove element m[k] from map m
We already looked at clear
, which deletes everything in a map. delete
lets you surgically remove individual keys from a map.
Unlike some languages, which give you the means to return an element as it’s deleted, if you want to do that in Go, you’ll need to do it in two steps:
var m := map[string]int{
"Bob": 32,
"Alice": 28,
"Chuck": 40,
}
x := m["Bob"] // x: 32
delete(m, "Bob") // m: {"Alice": 28, "Chuck": 40}
If the type of
m
is a type parameter, all types in that type set must be maps, and they must all have identical key types.
Notably, they don’t need to have identical value types.
func deleteAndReturn[M map[string]T, T any](m M, key string) T {
x := m[key]
delete(m, key)
return x
}
If the map
m
isnil
or the elementm[k]
does not exist,delete
is a no-op.
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)