Issue 23748 - associative arrays need 2 lookups to remove and extract, should be 1
Summary: associative arrays need 2 lookups to remove and extract, should be 1
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: druntime (show other issues)
Version: D2
Hardware: All All
: P4 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2023-02-27 17:02 UTC by Bolpat
Modified: 2024-12-07 13:42 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Bolpat 2023-02-27 17:02:22 UTC
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 dlangBugzillaToGithub 2024-12-07 13:42:29 UTC
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