Closed
Description
It would be good if the delete
function returns a bool indicating if the key was found or not. if it was found, it returns true and the key is obviously deleted.
In my article: https://medium.com/swlh/ordered-maps-for-go-using-generics-875ef3816c71#4102, you can see that after I attempt to delete a key from the map, I have to do an expensive operation (optimising the data struct using linked list is besides the point). The operation only needs to be done if the key exists.
I can't check existence for key first and then attempt to delete because it's not atomic.
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
seankhliao commentedon Aug 29, 2020
You mention check-then-delete is not atomic, which indicates you want them for concurrent use, but maps are not safe for concurrent use without synchronization, so the correct solution would be to introduce a lock or some other method of synchronization which would also cover check-then-delete
pjebs commentedon Aug 29, 2020
Using a synchronisation mechanism is overkill in my situation. I just need to be informed if the
delete()
actually deleted a key or not. Internally, the function has that information. It just needs to release it.pjebs commentedon Aug 29, 2020
On second thoughts, you are correct but I still think this proposal provides benefits with no cost and is backward compatible
[-]builtin: delete returns bool (atomic)[/-][+]proposal: builtin: delete returns bool (atomic)[/+]ianlancetaylor commentedon Aug 30, 2020
See https://www.reddit.com/r/golang/comments/5tfx7i/why_delete_doesnt_return_a_bool/ddmo4ug?utm_source=share&utm_medium=web2x&context=3
[-]proposal: builtin: delete returns bool (atomic)[/-][+]proposal: builtin: delete returns bool[/+]rsc commentedon Sep 2, 2020
In the non-atomic case, this boils down to:
This seems like pretty clear code.
The only real argument against it is that it might be inefficient to do the hash twice.
We could fix that in the compiler (#5147) if needed.
It doesn't seem worth a language change.
But you wrote:
If there are other map changes happening at the same time, your code is unsafe and will crash, either from the race detector or from the map implementation's own race detector. Adding an 'atomic' delete would require synchronizing every write and delete just in case there was a racing write, which would slow down all accesses. That's why maps aren't atomic in the first place.
Given that maps aren't atomic and you need an atomic operation, I think it's safe to say this is infeasible.
mewmew commentedon Sep 2, 2020