dictionarygopointersdefer-keyword

Can I use defer to delete an element of a map?


type Tasks map[int]CustomValue

func (t *Tasks) Put(task MyTask) {
    (*t)[len(*t)] = task
    return len(*t) - 1
}

func (t *Tasks) Get(taskID int) interface{} {
    defer func() {         // Is this OK???
        delete(*t, taskID)
    }()
    return (*t)[jobID].GetValue()
}

Here is my code of Go. Basically, I'm using a map to store some "key-value"s. And I have two functions Put and Get.

After getting the value, I want to delete the element from the map.

Can I simply use the defer mechanism to do so? I don't know if the defer function must be invoked after return.


Solution

  • Yes, defer may be used to remove an element from the map like you intend to use it.

    Spec: Defer statements:

    ...if the surrounding function returns through an explicit return statement, deferred functions are executed after any result parameters are set by that return statement but before the function returns to its caller.

    So (*t)[jobID].GetValue() will be evaluated before the deletion in the deferred function happens.

    Note however that maps are pointers under the hood (for details see why slice values can sometimes go stale but never map values?), so you should use non-pointer receiver. This also simplifies your code a lot, and will make it more efficient.