user5047085
user5047085

Reputation:

Determining if delete actually removed an existing key in a map

I have a map called nearby

func Delete(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    delete(nearby, params["id"])
}

I want to find out if the delete() call actually found a key to delete, I tried reading the return value:

func Delete(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    result := delete(nearby, params["id"])
}

but the compiler didn't like that - how can I find out if a key/val was deleted?

Upvotes: 3

Views: 2779

Answers (2)

Thundercat
Thundercat

Reputation: 120999

Probe the map before deleting the value:

func Delete(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    _, deleted := nearby[params["id"]]
    delete(nearby, params["id"])
    fmt.Println(deleted)
}

This snippet and the code in the question have a data race because HTTP handlers can be called concurrently. Add a mutex to protect the map.

var (
    nearby = make(map[string]string)
    mu     sync.Mutex
)

func Delete(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    mu.Lock()
    _, deleted := nearby[params["id"]]
    delete(nearby, params["id"])
    mu.Unlock()
    fmt.Println(deleted)
}

Upvotes: 5

Michael Hampton
Michael Hampton

Reputation: 9980

The Go builtin delete() doesn't return anything, so you can't tell whether it deleted anything.

But you can check if the map contains the key and delete() it if it is present.

if _, ok := nearby[params["id"]]; ok {
    delete(nearby, params["id"])
} else {
    // whatever
}

Upvotes: 3

Related Questions