[Issue 23748] New: associative arrays need 2 lookups to remove and extract, should be 1

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Feb 27 17:02:22 UTC 2023


https://issues.dlang.org/show_bug.cgi?id=23748

          Issue ID: 23748
           Summary: associative arrays need 2 lookups to remove and
                    extract, should be 1
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: druntime
          Assignee: nobody at puremagic.com
          Reporter: qs.il.paperinik at gmail.com

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`).

--


More information about the Digitalmars-d-bugs mailing list