Feature to get or add value to an associative array.
Giles Bathgate
giles.bathgate at gmail.com
Sun Apr 15 22:52:47 UTC 2018
Hi,
I wanted a way to lazily insert a value into an associative
array, and I am proposing a new function called getOrAdd in
https://github.com/dlang/druntime/pull/2162
The function provides a means to get a value corresponding to the
key, but if the value doesn't exist it will evaluate the lazy
argument to create a new value, add this to the associative array
and then return it.
```
auto p = lookup.getOrAdd("giles", new Person);
p.eyeColor = Color.Brown;
//...
assert("giles" in lookup);
```
Corresponding documentation added in
https://github.com/dlang/dlang.org/pull/2343
Implementation details:
Traditionally the above example could be done like so:
```
auto p = "giles" in lookup;
if (p is null) {
p = new Person;
lookup["giles"] = p;
}
p.eyeColor = Color.Brown;
//...
assert("giles" in lookup);
```
I find this later code clunky and it requires two hashes/lookups.
The proposed implementation adds support directly to rt/aaA.d to
avoid this. I should also point out that the allocation of a new
Person in the example is trivial, but it might often be the case
that the person instance is created by fetching a record from a
db, or an Image loaded from disk, or a movie downloaded from the
internet.
More information about the Digitalmars-d
mailing list