warvariuc
warvariuc

Reputation: 59604

Pop a value from a map using one lookup

How to implement in Go a function that pops a key from a map using just one lookup? This version does two lookups on the map:

package main

import "fmt"

func main() {
    m := map[string]int{"a":1, "b":2}
    a, ok := m["a"]
    if ok {
        delete(m, "a")
    }
    fmt.Println(a, m)
}

I checked maybe delete returns the value of deleted key:

package main

func main() {
    m := map[string]int{"a":1, "b":2}
    println(delete(m, "a"))
}

But this doesn't work:

prog.go:5: delete(m, "a") used as value

Upvotes: 1

Views: 6543

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109388

Go doesn't have a Pop function for maps, so there will always be 2 operations, a index and a delete.

If you're worried about verbosity and performance, and small helper function like so would be inlined, so there's no extra runtime overhead to using it.

func pop(m map[string]int, key string) (int, bool) {
    v, ok := m[key]
    if ok {
        delete(m, key)
    }
    return v, ok
}

Upvotes: 5

Related Questions