Skip to content

sync: Map method suggestions #21199

Closed
Closed
@pcostanza

Description

@pcostanza

Please answer these questions before submitting your issue. Thanks!

What version of Go are you using (go version)?

1.9rc1

What operating system and processor architecture are you using (go env)?

macOS, x86_64

What did you do?

If possible, provide a recipe for reproducing the error.
A complete runnable program is good.
A link on play.golang.org is best.

This is not an error report, but a report that I am convinced there are methods that still need to be added to the sync.Map data structure.

  1. A general-purpose Modify method is missing that allows modifying a value that is already stored in the map to a new value that depends on the old value. For example:
m.Modify(key, func(value interface{}, ok bool) (newValue interface{}, store bool) {
  if ok {
    newValue = value.(int) + 1
  } else {
    newValue = 1
  }
  store = true // false means: delete the current entry
  return
})

It's important that the key-value-pair currently stored in the map is not concurrently changed while the user-supplied function is being executed.

  1. Similarly, a DeleteOrStore method is missing:

actual, loaded := m.DeleteOrStore(key, value interface{})
// loaded = true means there was already a value in the map, which is now deleted
// loaded = false means there wasn't a value in the map, and value is now stored (== actual)

DeleteOrStore is useful if you are looking for pairs of entries that share the same key in a stream of entries: When the first entry arrives, it is stored in the map because no entry in the map with the same value already existed; when the second entry arrives, the first entry is retrieved and deleted from the map, and the pair of entries can now be processed outside of the map. A real-world use case is the processing of read pairs in DNA sequencing pipelines. (I can provide more details and code if there is interest.)

  1. I also believe that LoadOrCompute could be useful:

m.LoadOrCompute(key, func() interface{} { return some computed value })
This could be useful if computing a new value is expensive for some reason. Likewise, a DeleteOrCompute is potentially useful.

I don't know good use cases for LoadOrCompute and DeleteOrCompute, though, unlike for Modify and DeleteOrStore.

What did you expect to see?

I expected to see at least methods Modify and DeleteOrStore on sync.Map

What did you see instead?

These methods are not defined.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions