2

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?

  • 1
    Related: [How to check if a map contains a key in go?](https://stackoverflow.com/q/2050391/1068283) – Michael Hampton Oct 24 '18 at 02:46
  • 1
    I see your `delete()` is part of an http request. It's actually not bad design-wise to keep it this way, as the request stays idempotent (ie multiple delete operations end up with the same result). – jonathangersam Oct 24 '18 at 03:11

2 Answers2

4

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)
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • upvoted..why doesn't golang offer something builtin that can return whether `delete()` did anything? fml. why not another utility called `deletem()` or anything really –  Oct 24 '18 at 02:48
  • Even I'll go with this answer as you did mention that concurrent writes to a map aren't safe. There are probably several other places where you modify this map that should also be protected with this same mutex. – Michael Hampton Oct 24 '18 at 02:53
  • @MrCholo See https://www.reddit.com/r/golang/comments/5tfx7i/why_delete_doesnt_return_a_bool/ for discussion on delete return value. – Charlie Tumahai Oct 24 '18 at 02:54
3

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
}
Michael Hampton
  • 9,737
  • 4
  • 55
  • 96