Deletion of map elements

September 10, 2024

Deletion of map elements

The built-in function delete removes the element with key k from a map m. The value k must be assignable to the key type of m.

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 is nil or the element m[k] does not exist, delete is a no-op.

Quotes from The Go Programming Language Specification Language version go1.23 (June 13, 2024)


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe