Deletion of map elements
The built-in function
deleteremoves the element with keykfrom a mapm. The valuekmust 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
mis 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
misnilor the elementm[k]does not exist,deleteis a no-op.
Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)