Bug 23748 – associative arrays need 2 lookups to remove and extract, should be 1

Status
NEW
Severity
enhancement
Priority
P4
Component
druntime
Product
D
Version
D2
Platform
All
OS
All
Creation time
2023-02-27T17:02:22Z
Last change time
2024-12-07T13:42:29Z
Assigned to
No Owner
Creator
Bolpat
Moved to GitHub: dmd#17204 →

Comments

Comment #0 by qs.il.paperinik — 2023-02-27T17:02:22Z
There is no way to remove a key–value pair and extract the value with one lookup. One has to make one lookup to get the value (if any), and another to remove the pair. Currently, the `remove` function returns a `bool` value indicating via `true` that a key–value pair with the passed `key` was present, and `false` when it was not. This could be improved by instead returning a pointer to the value if they pair existed, and `null` otherwise, i.e. exactly what `in` does, but additionally removing the value. With this enhancement, extract–remove is a trivial one-liner. Compare this: ```d Value* v = key in aa; aa.remove(key); if (v != null) { // handle the value // *v is valid even after removal. } ``` with this: ```d if (Value* v = aa.remove(key)) { // handle the value } ``` There should be minimal breakage because most current uses of `remove` will ignore its result anyways, and if not, the returned pointer converts to `true` implicitly if it is not `null` and `null` to `false` in contexts where a `bool` is required. If that breakage cannot be tolerated or the new implementation is deemed considerably more expensive than current `remove`, I suggest a new function by the name `removeAndExtract` or (cf. Scott Mayers: `takeOut`).
Comment #1 by robert.schadek — 2024-12-07T13:42:29Z
THIS ISSUE HAS BEEN MOVED TO GITHUB https://github.com/dlang/dmd/issues/17204 DO NOT COMMENT HERE ANYMORE, NOBODY WILL SEE IT, THIS ISSUE HAS BEEN MOVED TO GITHUB