Skip to content

sync: add new Map method LoadAndDelete #33762

@wkonkel

Description

@wkonkel

Problem

It is not currently possible to determine if a value was deleted from a sync.Map. For example:

actual, ok := m.Load("key")
if ok {
  m.Delete("key")
  doSomething(actual)
}

This is not atomic in that another goroutine could Delete the value between Load and Delete and doSomething() would be called twice.

Previous issues #25396 and #23547 suggested modifying Delete signature which would break backwards compatibility.

Solution

Create a new function:

func DeleteWithLoad(key interface{}) (actual interface{}, deleted bool)

If the key is found in the map, this function would return the deleted value and true. If the value is not found, this would return nil, false. The above code would then become:

actual, deleted := m.DeleteWithLoad("key")
if deleted {
  doSomething(actual)
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions